Pregunta

Having following class with NSMutableDictionary* property

@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);
}

The output is

2014-02-23 19:05:44.110 MyProj[12818:303] Count: 0
2014-02-23 19:05:44.110 MyProj[12818:303] Count: 1

Why self.dict is not modified?

UPD Used MyClass * obj = [MyClass alloc] instead of MyClass * obj = [[MyClass alloc] init], so init has not been called.

¿Fue útil?

Solución

It is necessary to instantiate the dict property, this can be done in the init method.

Sample:

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

Call with:

MyClass *myClass = [MyClass new];
[myClass method];
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top