Stofke
Stofke

Reputation: 2968

Can't add values to a NSMutableDictionary

I have a loop which creates a key (based on the alphabet) and value an empty array.

-(id)init
{
    if (self = [super init]){
        addressbook=[[NSMutableDictionary alloc] init];
        //loop over the alphabetArray and add to an adressbook dictionary
        for(char a = 'a'; a <= 'z'; a++){
            NSMutableArray * personenArrayTemp = [[NSMutableArray alloc] init];
            [addressbook setValue:personenArrayTemp forKey:[NSString stringWithFormat:@"%c", a]];   
        }
    }   
    return self;
}

Next I add a person to my addressbook by getting the first letter of the name and using that to look up the key for that letter in the addressbook. Once found I add the person object.

-(void)addAddressbook:(Persoon *)persoon{
    NSString *firstLetter = [persoon.naam substringToIndex:1];
    [[addressbook objectForKey:firstLetter] addObject:persoon];
    //NSLog(@"%@",firstLetter);
    for(NSString *key in addressbook){
        NSLog(@"key=%@ , value=%@ ", key,[addressbook objectForKey:key]);
    }  
}

The NSLog in the for loop just returns this:

2012-02-27 16:26:20.152 Adresboek[4828:503] key=p , value=(
) 
2012-02-27 16:26:20.155 Adresboek[4828:503] key=c , value=(
) 
2012-02-27 16:26:20.190 Adresboek[4828:503] key=b , value=(
) 
.
.
.
2012-02-27 16:26:20.223 Adresboek[4828:503] key=o , value=(
) 

All values are empty.

SOLVED, it returned an uppercase letter

Upvotes: 0

Views: 432

Answers (1)

Tim Dean
Tim Dean

Reputation: 8292

First of all, you are adding the same NSMutable array instance to all of the keys in your NSDictionary. So no matter what you add (or don't add), the results for each key in your output will always be identical. If that is not what you are intending, then you need to move the temp array creation inside your loop:

//loop over the alphabetArray and add to an adressbook dictionary
for(char a = 'a'; a <= 'z'; a++){
    NSMutableArray * personenArrayTemp = [[NSMutableArray alloc] init];
    [addressbook setValue:personenArrayTemp forKey:[NSString stringWithFormat:@"%c", a]];   
}

Now, the question is why nothing is getting added. I suspect that if you look at the value of [addressbook objectForKey:firstLetter] it is probably nil, so when you add your object to it nothing happens. It's hard to say exactly why this would happen: You'd have to look at what is being passed into your function as persoon.naam and what is being returned into your firstLetter variable. Is firstLetter really the same string as what you are using as indices in your dictionary?

Upvotes: 1

Related Questions