想在category中新增个属性来用,创建的可变字典属性,也做了相关关联,结果用不了setobject方法,打印出来一看发现变成了不可变字典类型,希望有大神帮我看看哪里出问题了:
static void *myAllPropertiesDicKey = &myAllPropertiesDicKey;
@implementation FatherClass (Category)
//add setter and getter method in runtime
-(void)setMyAllPropertiesDic:(NSMutableDictionary *)myAllPropertiesDic{
objc_setAssociatedObject(self, & myAllPropertiesDicKey, myAllPropertiesDic, OBJC_ASSOCIATION_COPY);
}
-(NSMutableDictionary )myAllPropertiesDic{
return objc_getAssociatedObject(self, &myAllPropertiesDicKey);
}
//
-(instancetype)initByAllPropertiesInMyDictionary{
if (self = [super init]) {
//declare a variable to save the number of properties
unsigned int count;
//get all the properties
objc_property_t properties = class_copyPropertyList([self class], &count);
//init the mutabledictionary used to save all properties
self.myAllPropertiesDic = [[NSMutableDictionary alloc]initWithCapacity:count];
//deal with each property
for (int i=0; i<count; i++) {
objc_property_t property = properties[i];
const char* char_f = property_getName(property);
NSString* propertyName = [NSString stringWithUTF8String:char_f];
id propertyValue = [self valueForKey:propertyName];
if (![propertyName isEqualToString:@"myAllPropertiesDic"]) {
if ([self.myAllPropertiesDic isKindOfClass:[NSMutableDictionary class]]) {
NSLog(@"可变");
}else if ([self.myAllPropertiesDic isKindOfClass:[NSDictionary class]]){
NSLog(@"不可变");
}else{
NSLog(@"p都不是");
}
[self.myAllPropertiesDic setObject:propertyValue?propertyValue:[NSNull null] forKey:propertyName];
[self addObserver:self forKeyPath:propertyName options:NSKeyValueObservingOptionNew context:nil];
}
}
free(properties);
}
return self;
}
打印出来是:2016-04-25 16:31:36.551 test2[1375:54201] 不可变
你用runtime创建字典是用的是copy修饰符导致你的字典是不可变,应该用strong修饰符,改了就好用了
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。