开发者社区> 问答> 正文

关于 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] 不可变

展开
收起
爵霸 2016-03-06 08:39:17 2343 0
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

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

    2019-07-17 18:53:55
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
手淘iOS性能优化探索 立即下载
From Java/Android to Swift iOS 立即下载
深入剖析iOS性能优化 立即下载