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