12

I'm having troubles with creating NSDictionaries in a loop and adding it to an NSMutableArray.

Basically I just want to change the names of the keys, but since I couldn't find a function for that I went for following code:

- (NSMutableArray *)getCategoriesForChannel:(int)channelId {
    NSDictionary *data = [self call:@"get_categories.ashx"];
    NSArray *categories = [data objectForKey:@"categories"];
    NSMutableArray *returnArray = [NSMutableArray
                          arrayWithCapacity:[categories count]];

    for(NSDictionary *category in categories) {
        [returnArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                         [category objectForKey:@"Channel_id"], @"id",
                         [category objectForKey:@"Channel_name"], "@name", nil]];
    }
    return returnArray;
}

But app always quits when it reaches the addObject: method and throws an EXC_BAD_ACCESS. I think that it has got something to do with memory management, but since I don't really have a C-background I have no idea how to solve this issue. Can someone please point me to the right direction? Thanks in advance!

NSGod
  • 22,699
  • 3
  • 58
  • 66
Lucas G
  • 148
  • 1
  • 7

2 Answers2

29
[returnArray addObject:
    [NSDictionary dictionaryWithObjectsAndKeys:
    [category objectForKey:@"Channel_id"], @"id",
    [category objectForKey:@"Channel_name"], "@name", nil]];

If this is in fact the code you have (and the typo wasn't introduced while writing it in your web browser), notice that the last key you have is "@name" instead of @"name". That would effectively be a C-string, rather than an NSString, which can't properly be added into an NSArray (or most collection classes, for that matter).

NSGod
  • 22,699
  • 3
  • 58
  • 66
2

Within the loop can you NSLog this [category objectForKey:@"Channel_id"] and [category objectForKey:@"Channel_name"]? I suspect one is giving nil and causing the trouble. Not sure. Just a guess.

hol
  • 8,255
  • 5
  • 33
  • 59