NSMutableDictionary类属性未在方法中修改

时间:2014-02-23 15:13:33

标签: 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];
    }

    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

1 个答案:

答案 0 :(得分:0)

有必要实例化dict属性,这可以在init方法中完成。

样品:

- (instancetype)init {
    self = [super init];
    if (self) {
        _dict = [NSMutableDictionary new];
    }
    return self;
}

致电:

MyClass *myClass = [MyClass new];
[myClass method];