objective c - Button Action addTarget call another class method with singleton shareInstance, and send with dynamic parameter -


i want design user story when user click uibutton "choose fruit" on class call choosefruit method on class b different parameter, such banana, apple, orange. requirement, search internet found out use shareinstance (singleton pattern) can achieve call class method. people shareinstance not recommend send parameter. (https://stackoverflow.com/a/28652715/8305553)

but every time button clicked, must send different fruit method. here code, believe way not best practice. can provide better way to approach user story?

choosefruitviewcontroller.m:

@implementation choosefruitviewcontroller {     nsstring *fruit; }  uibutton *choosefruit = [[uibutton alloc] initwithframe:cgrectmake(20, 200, 150, 40)]; [choosefruit settitle:@"choose fruit" forstate: uicontrolstatenormal]; [choosefruit setbackgroundcolor: [uicolor bluecolor]]; choosefruitclass *choosefruitclasstest = [choosefruitclass sharedinstance]; fruit = @"banana"; [choosefruitclasstest setfruit:fruit]; [choosefruit addtarget: choosefruitclasstest action:@selector(testalert:) forcontrolevents: uicontroleventtouchupinside]; [self.view addsubview: choosefruit]; 

choosefruit.h:

#import <foundation/foundation.h>  @interface choosefruit: nsobject @property (nonatomic, retain) nsstring *fruit; +(choosefruit *)sharedinstance; -(void)setfruit:(nsstring *)fruit; @end 

choosefruit.m:

#import "choosefruit.h"  @interface choosefruit() -(void)testalert: (id)target; @end  @implementation choosefruit + (choosefruit *)sharedinstance {     static choosefruit *sharedinstance = nil;     static dispatch_once_t oncetoken;     dispatch_once(&oncetoken, ^{         sharedinstance = [[self alloc] init];     });     return sharedinstance; }  - (void)setfruit:(nsstring *)fruit {     if (self) {         _fruit = fruit;     } }  -(void)testalert: (id)target {     uialertview *alert = [[uialertview alloc] initwithtitle:_fruit message:nil delegate:target cancelbuttontitle:@"ok" otherbuttontitles:nil];     [alert show];     [alert release]; } 


Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -