xuanwenchao
xuanwenchao

Reputation: 29

declare two property and call objc_setAssociatedObject with same key

in category UIButton .h file:

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

in category UIButton .m file: (note: all keys is 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

below is test code:

....
....
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);

output result:

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

I would like to know why it is correct for same key??? Thank you.

Upvotes: 0

Views: 290

Answers (1)

Dan Shelly
Dan Shelly

Reputation: 6011

see here

You used objc_getAssociatedObject and objc_setAssociatedObject with the same key for both parameters, so they set/get the same object

Upvotes: 1

Related Questions