0

Why is the count of otherArray 0 even though self.array has N items and the for loop is executing N times?

for (MyObject *obj in self.array) 
{
    [self.otherArray addObject:obj];
    NSLog(@"Num items: %d", [self.otherArray count]);
} 

self.otherArray is an NSMutableArray*

LATER: Doh!, forgot to call alloc/init (I come from a language where the equivalent of addObejct will create the array if necessary).

PengOne
  • 48,188
  • 17
  • 130
  • 149
Gruntcakes
  • 37,738
  • 44
  • 184
  • 378
  • possible duplicate of [NSMutableArray addObject not affecting count?](http://stackoverflow.com/questions/3683761/nsmutablearray-addobject-not-affecting-count) and [NSMutableArray addObject: not working](http://stackoverflow.com/questions/1827058/nsmutablearray-addobject-not-working) – jscs Jan 12 '12 at 18:47

2 Answers2

2

Best guess: You have not initialized self.otherArray correctly.

Second best guess: self.otherArray is not mutable.

Test this by posting your initialization code.

PengOne
  • 48,188
  • 17
  • 130
  • 149
  • Doh, didn't call alloc/init (I've come from a language where the equivalent of calling addObject will also create the array if necessary.) – Gruntcakes Jan 12 '12 at 18:47
  • @Mungbeans You are not alone in this mistake. Let me know if that doesn't fix the issue. – PengOne Jan 12 '12 at 18:47
0

In this case, the most common reason this would occur is if self.otherArray isn't initialized. If you add a check to self.otherArray, I would suspect it is nil. If you added:

self.otherArray = [[NSMutableArray alloc] init];

right before the other code, I suspect it would work as intended.

dtuckernet
  • 7,817
  • 5
  • 39
  • 54