The same class has multiple Alertview, different Alertview Click OK button to execute different methods
Alertone Click OK button to execute MethodOne, alerttwo Click OK button to execute Methodtwo
Initialize and display Alertone
-(Ibaction) Showalertone: (ID) Sender {uialertview *alertone = [Uialertview alloc]initwithtitle:@ "Alertone" message:@ " "Delegate:self cancelbuttontitle:@" Cancel "otherbuttontitles:@" OK ", nil]; [Alertone settag:1]; [Alertone show];}
Initialize and display Alerttwo
-(Ibaction) Showalerttwo: (ID) Sender {uialertview *alerttwo = [Uialertview alloc]initwithtitle:@ "Alerttwo" message:@ " "Delegate:self cancelbuttontitle:@" Cancel "otherbuttontitles:@" OK ", nil]; [Alerttwo Settag:2]; [Alerttwo show];}
-(void) Alertview: (uialertview *) alertView Clickedbuttonatindex: (Nsinteger) buttonindex{ if (buttonindex == 0) { return; } if (alertview.tag == 1) { if ( BUTTONINDEX == 1) { [ self methodone]; } } else if (alertview.tag == 2) { if (buttonindex == 1) { [self methodtwo]; } }}
- Associated Object Procedure
Import runtime.h, defining attribute Association key
#import "ViewController.h" #import <objc/runtime.h>static void *alertviewkey = "Alertviewkey";
Initialize and display Alertone, define block, associate block with Alertone
- (Ibaction) Showalertone: (ID) sender { uialertview *alertone = [[uialertview alloc]initwithtitle:@ "AlertOne" message:@ "" delegate:self cancelbuttontitle:@ "Cancel" otherbuttontitles:@ "OK", nil]; void (^block) (Nsinteger) = ^ (nsinteger buttonindex) { if (buttonindex == 1) { [self methodOne]; } }; objc_setassociatedobject (alertOne, alertviewkey, block, objc_association_copy);//Associate block with alertOne [alertone show];
initializes and displays alerttwo while defining block, Associate block with Alerttwo
- (Ibaction) Showalerttwo: (ID) sender { uialertview *alerttwo = [[uialertview alloc]initwithtitle:@ "AlertTwo" message:@ "" delegate:self cancelbuttontitle:@ "Cancel" otherbuttontitles:@ "OK", nil]; void (^block) (Nsinteger) = ^ (nsinteger buttonindex) { if (buttonindex == 1) { [self methodTwo]; } }; objc_setassociatedobject (alertTwo, alertviewkey, block, objc_association_copy); [alerttwo show];}
Implement the proxy, in the proxy method, directly take out the current alert associated with the block, and then pass the Buttonindex, let block itself call the corresponding method
-(void) Alertview: (Uialertview *) Alertview Clickedbuttonatindex: (Nsinteger) buttonindex{if (Buttonindex = = 0) {R Eturn; } void (^block) (Nsinteger) = Objc_getassociatedobject (Alertview, Alertviewkey); Block (Buttonindex);}
There are several advantages to using the associated object method:
Simplified Generation Code
Make the code level clear
Take advantage of object-to-property ownership relationships
IOS Runtime association objects (associated object)