added objects to nsmutablearray, yet the array is null

Discussion in 'Mac Programming' started by johnmerlino, Nov 11, 2011.

  1. johnmerlino macrumors member

    Oct 22, 2011
    Hey all,
    I have an nsmutablearray declared in interface:

    @interface UnitsDetailViewController : UITableViewController
    NSMutableArray *units;

    Then I try to add objects to it (and I verified that the objects exist via NSLog):
                NSLog(@"the units object contains %@", [unit objectForKey:@"id"]);
                NSLog(@"the units object contains %@", [unit objectForKey:@"name"]);
                Unit *model = [[Unit alloc] init];
                model.unit_id = [unit objectForKey:@"id"];
       = [unit objectForKey:@"name"];
                NSLog(@"the model property contains %@", model.unit_id);
                NSLog(@"the model property contains %@",;
                NSLog(@"the model itself contains %@", model); //<Unit: 0x6bc6150>
                [units addObject:model];
                NSLog(@"the units object contains %@", units);
    Yet the last NSLog above where I evaluate value of units, it returns null. I expect it to return an array of objects.

    thanks for response
  2. Catfish_Man macrumors 68030


    Sep 13, 2001
    Portland, OR
    It looks like you never actually created the array, just declared it.
  3. lee1210 macrumors 68040


    Jan 10, 2005
    Dallas, TX
    You may be left wondering why you were allowed to add an item when you never allocated an array. The reason is that you can send messages to nil and they don't fail, it's just a no-op. This can be helpful when you know it and do this purposefully, but obviously can cause some confusion. Alloc and init yourself an array (perhaps in your init, or lazy load when you need it) and you should be good to go.

    Where are you learning from? Your posts have shown some gaps in your basic understanding, which is completely normal for a beginner, but you should have a resource other than us to learn from.

  4. PatrickCocoa macrumors 6502a

    Dec 2, 2008

    In your interface, what you're doing is (merely) telling the rest of your code that if they use that class, the variable (in this case "unit") is available for that other code to use.

    In your implementation (which you have labeled "code"), you need to allocate and initialize that variable, then put stuff in it. You should be able to send an allocate message to the NSMutableArray class, then send a initialize message to the result, then assign that to the variable.
  5. johnmerlino thread starter macrumors member

    Oct 22, 2011
    Thanks for responses. Everyone was right here. I didnt initialize the array. I just declared it. I should have known this.

Share This Page