Jorge
Jorge

Reputation: 1532

Why is my setter method not getting called?

I have this in my .h file: @property (nonatomic, strong) NSMutableDictionary *valoresTotaisNutricao;

And then, I override setter and getter like this:

-(void)setValoresTotaisNutricao:(NSMutableDictionary *)valoresTotaisNutricao
{
    NSLog(@"setter");
    [self oDicionarioEdeHoje];
    if ([self oDicionarioEdeHoje] == NO) {
        // Data não está atualizada, apagar dicionário e setar nova.
        [_valoresTotaisNutricao removeAllObjects];
        [_valoresTotaisNutricao setObject:[self pegarFinalDoDia] forKey:@"data"];
    }
    _valoresTotaisNutricao = valoresTotaisNutricao;
}

-(NSMutableDictionary *)valoresTotaisNutricao
{
    NSLog(@"getter");
    if (!_valoresTotaisNutricao) {
        _valoresTotaisNutricao = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[self pegarFinalDoDia], @"data", nil];
    }
    return _valoresTotaisNutricao;
}

And I use @synthesize valoresTotaisNutricao = _valoresTotaisNutricao;.

My getter works, but my setter never gets called. I tried to explicit declare the method name on the @property declaration but it didn't work as well.

UPDATE:

I try to add some values to the NSMutableDictionary from another class.

[singleton.valoresTotaisNutricao setObject:[NSNumber numberWithInt:222] forKey:@"teste"];.

Upvotes: 0

Views: 350

Answers (1)

TylerP
TylerP

Reputation: 9829

setObject:forKey: does not call your setter method.

singleton.valoresTotaisNutricao will call your getter method, which you have lazily-loading your property, and then setObject:[NSNumber numberWithInt:222] forKey:@"teste" will set a value for the key of @"teste" on that dictionary, but nowhere in that code does your setter method get called.

You would need to use either this:

singleton.valoresTotaisNutricao = <some mutable dictionary object>;

or this:

[singleton setValoresTotaisNutricao:<some mutable dictionary object>];

... to call your setter method.

Upvotes: 4

Related Questions