#import "ViewController.h" #import <objc/runtime.h> //objc_AssociationPolicy 枚舉 對應等效的屬性 static void *EocMyAlertViewKey = @"EocMyAlertViewKey"; @interface ViewController ()<UIAlertViewDelegate> @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; // Do any additional setup after loading the view, typically from a nib. //管理關聯對象的方法 // objc_setAssociatedObject(id object, <#const void *key#>, <#id value#>, <#objc_AssociationPolicy policy#>)設置關聯對象值 // objc_getAssociatedObject(id object, <#const void *key#>)獲取關聯對象值 // objc_removeAssociatedObjects(<#id object#>) 移除指定對象的所有關聯對象 UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(200, 200, 100, 200)]; button.backgroundColor = [UIColor orangeColor]; [self.view addSubview:button]; [button addTarget:self action:@selector(action) forControlEvents:UIControlEventTouchUpInside]; } -(void)action { UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Question" message:@"What do you want to do" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Continue", nil]; void (^block)(NSInteger) = ^(NSInteger buttonIndex){ if (buttonIndex == 0 ){ [self doCancel:alert]; } else { [self doContinue]; } }; //1.定義關聯對象時 可指定內存管理語義,用以模仿定義屬性所採用的「擁有關係」與「非擁有關係」 objc_setAssociatedObject(alert, EocMyAlertViewKey, block,OBJC_ASSOCIATION_COPY); [alert show]; } -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { //2.經過關聯對象機制把兩個對象連起來 void (^block)(NSInteger) = objc_getAssociatedObject(alertView, EocMyAlertViewKey); block(buttonIndex); //3.只有在其餘作法不可行時才應選用關聯對象,由於這種方法一般會引入難以查找的bug } -(void)doCancel:(UIAlertView *)alert { NSLog(@"Calcel"); objc_removeAssociatedObjects(alert); } -(void)doContinue { NSLog(@"doContinue"); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end