声明两个属性并使用相同的键调用objc_setAssociatedObject

时间:2013-04-08 07:03:24

标签: iphone ios objective-c objective-c-category

类别UIButton .h文件:

@interface UIButton (zz)
@property (nonatomic,strong) NSString *param1;
@property (nonatomic,strong) NSString *param2;
@end

类别UIButton .m文件:(注意:所有键都为0)

@implementation UIButton (zz)
@dynamic param1;
@dynamic param2;

-(void)setParam1:(NSString *)param1{
     objc_setAssociatedObject(self, 0, param1, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(NSString*)param1{
    return (NSString *)objc_getAssociatedObject(self, 0);
}

-(void)setParam2:(NSString *)param2{
    objc_setAssociatedObject(self, 0, param2, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(NSString*)param2{
    return (NSString *)objc_getAssociatedObject(self, 0);
}

@end

下面是测试代码:

....
....
UIButton *b1 = [UIButton buttonWithType:UIButtonTypeCustom];
UIButton *b2 = [UIButton buttonWithType:UIButtonTypeCustom];

b1.param1 = @"b1 1111";
b1.param2 = @"b1 2222";

b2.param1 = @"b2 1111";
b2.param2 = @"b2 2222";

NSLog(@"b1 param1=%@ param2=%@",b1.param1,b1.param2);
NSLog(@"b2 param1=%@ param2=%@",b2.param1,b2.param2);

输出结果:

2013-04-08 11:30:52.258 zazis[928:c07] b1 param1=b1 2222 param2=b1 2222
2013-04-08 11:30:52.259 zazis[928:c07] b2 param1=b2 2222 param2=b2 2222

我想知道为什么它对于同一个键是正确的???   谢谢。

1 个答案:

答案 0 :(得分:1)

see here

您使用objc_getAssociatedObjectobjc_setAssociatedObject为两个参数使用相同的键,因此他们设置/获取相同的对象