Objective c 未在方法中修改NSMutableDictionary类属性
具有以下NSMutableDictionary*属性的类Objective c 未在方法中修改NSMutableDictionary类属性,objective-c,nsmutabledictionary,Objective C,Nsmutabledictionary,具有以下NSMutableDictionary*属性的类 @interface MyClass : NSObject @property(retain,atomic) NSMutableDictionary* dict; - (void) method; @end - (id) init{ self = [super init]; if(self){ self.dict = [NSMutableDictionary dictionary]; }
@interface MyClass : NSObject
@property(retain,atomic) NSMutableDictionary* dict;
- (void) method;
@end
- (id) init{
self = [super init];
if(self){
self.dict = [NSMutableDictionary dictionary];
}
return self;
}
- (void) method
{
NSMutableDictionary* dict = [NSMutableDictionary dictionary];
self.dict[@"Test"] = @"Shmest";
dict[@"Test"] = @"Shmest";
NSLog(@"Count: %ld",[self.dict allKeys].count);
NSLog(@"Count: %ld",[dict allKeys].count);
}
输出是
2014-02-23 19:05:44.110 MyProj[12818:303] Count: 0
2014-02-23 19:05:44.110 MyProj[12818:303] Count: 1
为什么不修改self.dict
UPD
使用了
MyClass*obj=[MyClass alloc]
而不是MyClass*obj=[[MyClass alloc]init]
,因此未调用init
有必要实例化dict
属性,这可以在init
方法中完成
样本:
- (instancetype)init {
self = [super init];
if (self) {
_dict = [NSMutableDictionary new];
}
return self;
}
致电:
MyClass *myClass = [MyClass new];
[myClass method];
你在哪里设置self.dict?在您为dict属性设置值之前,它将是nil,因此其行为与代码中的一样。我正在init method(添加到post body)中设置它。将
NSLog(dict)
添加到method
以检查to是否已初始化。它未初始化,我的错误。使用了MyClass*obj=[MyClass alloc]
而不是MyClass*obj=[[MyClass alloc]init]
;非常感谢`请看一下我在帖子中添加的init
方法。有什么不对劲吗?(new
、dictionary
和alloc
的行为方式相同:新值不会添加到dict中)我刚刚测试了您的代码,它正常工作。我必须添加@implementation-MyClass
和结尾@end
。