扫码关注官方订阅号
博客上说:category无法添加实例变量的局限可以使用字典对象解决请问这句话如何理解?
ringa_lee
你已经理解了前半句话,对于后半句,写几行代码验证如下:原有类,用字典保存了参数name和age:
@interface XObj : NSObject @property(nonatomic,retain) NSMutableDictionary *parms; -(void) printPerson; @end @implementation XObj @synthesize parms; -(void)printPerson { NSLog(@"[XObj] name = %@",[parms objectForKey:@"name"]); } @end
现在需要加入参数country,扩展方法printCountry(),因为category不能加实例变量,所以:
@implementation XObj(Utility) -(void)printCountry { NSLog(@"[XObj Utility] Country=%@",[self.parms objectForKey:@"Country"]); }
实际使用时,可以这样做:
int main(int argc, const char * argv[]) { @autoreleasepool { [NSStringUtility logURLAddress:@"http://www.baidu.com"]; XObj *xo=[[XObj alloc]init]; NSMutableDictionary *dict=[[NSMutableDictionary alloc]initWithObjectsAndKeys:@"A",@"name",@"18",@"age", nil]; xo.parms = dict; [xo printPerson]; [xo.parms setObject:@"China" forKey:@"Country"]; [xo printCountry]; } return 0; }
category可以添加实例变量,使用AssociatedObject
至少你要把上下文贴出来。。。
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
你已经理解了前半句话,对于后半句,写几行代码验证如下:
原有类,用字典保存了参数name和age:
现在需要加入参数country,扩展方法printCountry(),因为category不能加实例变量,所以:
实际使用时,可以这样做:
category可以添加实例变量,使用AssociatedObject
至少你要把上下文贴出来。。。