首页 > 依旧是category问题

依旧是category问题

博客上说:category无法添加实例变量的局限可以使用字典对象解决请问这句话如何理解?


你已经理解了前半句话,对于后半句,写几行代码验证如下:
原有类,用字典保存了参数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


至少你要把上下文贴出来。。。

【热门文章】
【热门文章】