NSMutableDictionary empty when using for TableView

3278 views ios
-1

What I'm doing is list all the phone's contacts divided into section depending on their initial letter, but when accessing the Dictionary to populate my tableView it is always empty. Below is my current code:

for (MyContacts *obj in contactsArray) {
    NSString *name = [NSString stringWithFormat:@"%@", obj.givenName];
    NSString *firstChar = [name substringToIndex:1];
    NSMutableArray *arrayObject = [self.dictAlphabet objectForKey:firstChar];

    if (arrayObject == nil) {
        arrayObject = [NSMutableArray array];
        [self.dictAlphabet setObject:arrayObject forKey:firstChar];
    }

    [arrayObject addObject:obj];

} //dictAlphabet is a NSMutableDictionary declared on .h file

Ideally, it should look the array below:

dictAlphabet = @{@"A" : @[@"Anton"], @"B" : @[@"Baldo", @"Bohemian"], @"C" : @[@"Celestine", @"Clutch"]};

Any help on how can I implement this correctly? Thanks!

answered question

This question might have more to do with the lifecycle of the dictAlphabet. One common mistake is that it is never initialized to a new mutable dictionary. Could we see some NSLog evidence that it is a valid mutable dictionary before the loop, and really empty after?

1 Answer

12

You are adding the arrayObject in the dictionary first and then adding obj in the arrayObject which is causing the problem. Try doing this instead.

for (MyContacts *obj in contactsArray)
{
        NSString *name = [NSString stringWithFormat:@"%@", obj.givenName];
        NSString *firstChar = [name substringToIndex:1];
        NSMutableArray *arrayObject = [self.dictAlphabet objectForKey:firstChar];

        if (arrayObject == nil) {
            arrayObject = [NSMutableArray array];
        }
    [arrayObject addObject:obj];
    [self.dictAlphabet setObject:arrayObject forKey:firstChar];
}

posted this

Have an answer?

JD

Please login first before posting an answer.