2 ericarlene ericarlene 于 2016.04.25 16:47 提问

iOS中在类别中动态新增了的可变字典属性变成了不可变字典

想在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] 不可变
第一次发问题,谢谢大家了

1个回答

wang631106979
wang631106979   2016.04.29 10:25

你用runtime创建字典是用的是copy修饰符导致你的字典是不可变,应该用strong修饰符,改了就好用了

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!