[Objective-C]关联(objc_setAssociatedObject、objc_getAssociatedObject、objc_removeAssociatedObjects)
时间:2018-07-26 05:58:14来源:杰瑞文章网点击:作文字数:400字
作文导读:我的生日在我的眼里是非常重要的,像钻石一样重要,甚至比钻石还重要呢! 当时间已经和赛跑选手的速度快要跑到我的终点时,我一定会兴奋地跳跳去,像只猴子,因为我很期待收到生日礼物,
关联是指把两个对象相互关联起来,使得其中的一个对象作为另外一个对象的一部分。关联特性只有在Mac OS X V10.6以及以后的版本上才是可用的。- (void)viewDidLoad { [super viewDidLoad]; UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom]; [btn setTitle:@"按钮" forState:UIControlStateNormal]; [self.view addSubview:btn]; [btn setFrame:CGRectMake(50, 50, 50, 50)]; btn.backgroundColor = [UIColor redColor]; [btn addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside]; }-(void)click:(UIButton *)sender{ NSString *message = @"你是谁"; UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"我要传值·" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil]; alert.delegate = self; [alert show]; //#import头文件//objc_setAssociatedObject需要四个参数:源对象,关键字,关联的对象和一个关联策略。//1 源对象alert//2 关键字 唯一静态变量key associatedkey//3 关联的对象 sender//4 关键策略 OBJC_ASSOCIATION_ASSIGN// enum {// OBJC_ASSOCIATION_ASSIGN = 0, 若引用/**< Specifies a weak reference to the associated object. */// OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1, /**< Specifies a strong reference to the associated object.// * The association is not made atomically. */// OBJC_ASSOCIATION_COPY_NONATOMIC = 3, /**< Specifies that the associated object is copied.// * The association is not made atomically. */// OBJC_ASSOCIATION_RETAIN = 01401, /**< Specifies a strong reference to the associated object.// * The association is made atomically. */// OBJC_ASSOCIATION_COPY = 01403 /**< Specifies that the associated object is copied.// * The association is made atomically. */// };objc_setAssociatedObject(alert, @"msgstr", message,OBJC_ASSOCIATION_ASSIGN);//把alert和message字符串关联起来,作为alertview的一部分,关键词就是msgstr,之后可以使用objc_getAssociatedObject从alertview中获取到所关联的对象,便可以访问message或者btn了// 即实现了关联传值objc_setAssociatedObject(alert, @"btn property",sender,OBJC_ASSOCIATION_ASSIGN);}-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{//通过 objc_getAssociatedObject获取关联对象NSString *messageString =objc_getAssociatedObject(alertView, @"msgstr");UIButton *sender = objc_getAssociatedObject(alertView, @"btn property");NSLog(@"%ld",buttonIndex);NSLog(@"%@",messageString);NSLog(@"%@",[[sender titleLabel] text]);//使用函数objc_removeAssociatedObjects可以断开所有关联。通常情况下不建议使用这个函数,因为他会断开所有关联。只有在需要把对象恢复到“原始状态”的时候才会使用这个函数。}终端打印:2015-07-22 16:18:35.294 test[5174:144121] 02015-07-22 16:18:35.295 test[5174:144121] 你是谁2015-07-22 16:18:35.295 test[5174:144121] 点我补充:该方法在button addtarget的时候@selecter只能传一个sender。但是当想要传一个字典或者数组的时候,就可以使用关联的方法,将dict带入到我们的其他方法中。并通过get方法取出这个dict对象

[Objective-C]关联(objc_setAssociatedObject、objc_getAssociatedObject、objc_removeAssociatedObjects)一文由杰瑞文章网免费提供,本站为公益性作文网站,此作文为网上收集或网友提供,版权归原作者所有,如果侵犯了您的权益,请及时与我们联系,我们会立即删除!
杰瑞文章网友情提示:请不要直接抄作文用来交作业。你可以学习、借鉴、期待你写出更好的作文。
说说你对这篇作文的看法吧