【发布时间】:2014-02-23 15:13:33
【问题描述】:
具有以下具有 NSMutableDictionary* 属性的类
@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 没有被调用。
【问题讨论】:
-
你在任何地方设置 self.dict 吗?在为 dict 属性设置值之前,它将为 nil,因此其行为就像在您的代码中一样。
-
我在 init 方法中设置(添加到帖子正文)
-
将
NSLog(dict)添加到method以检查 to 是否已初始化。 -
它没有初始化,我的错。使用
MyClass * obj = [MyClass alloc]而不是MyClass * obj = [[MyClass alloc] init];非常感谢! `
标签: objective-c nsmutabledictionary