views:

3113

answers:

3

I'm sure I'm doing something silly, but this is driving me crazy.

I'm trying to loop through database results, create objects from those results, and add the objects to an NSMutableArray. I've verified via NSLog calls that the data is being correctly read from the database and copied to the object, but the count for the NSMutableArray always returns 0.

Here's the essence of the code:

while ([rs next]) {

 Kana *htemp = [Kana alloc];

 htemp.content = [rs stringForColumn:@"hiragana"];
 [hiragana addObject:htemp];

}
NSLog(@"Hiragana contains %d objects", [hiragana count]);

Kana is derived from NSObject, and hiragana is an instance of NSMutableArray.

I'm sure this is a rookie mistake, and I hope someone can set me straight. TIA! :)

A: 

A few things:

  1. What happens if you put an NSLog call inside of the while loop? Verify that loop iterations are actually happening before blaming it on the array.
  2. Where are you creating the array hiragana? If you are doing it incorrectly for some reason and the array is nil, it might cause problems like this.
  3. If you do not have garbage collection on, be sure to do [htemp release] after adding it to the loop. addObject retains and each added item will leak from the loop. Again, this is only relevant if garbage collection is off.

It's most likely either you aren't created the array correctly or rs doesn't contain what you expect it to contain, and so [rs next] isn't getting called ever (if rs is nil, for example, no iterations of this loop would execute and you wouldn't have any sort of error).

Joel Levin
Ahh... it was bad array initialization FTW! :) Thank you!
John Biesnecker
+15  A: 

My guess, judging from the code you posted, is that you probably aren't allocating your array properly. When creating objects, you need to initialize them as well. Therefore, this:

Kana *htemp = [Kana alloc];

Should be:

Kata *temp = [[Kana alloc] init];

All objects need to be initialized this way. Thus, if I'm correct and you haven't initialized your array, then your creation needs to go from this:

NSMutableArray *hiragana = [NSMutableArray alloc];

to this:

NSMutableArray *hiragana = [[NSMutableArray alloc] init];

For optimization reasons, you should probably also specify an initial capacity as well if you have any idea how many objects you might hold:

[[NSMutableArray alloc] initWithCapacity:someNumber];
Matt Ball
your answer is good - you should also include advice mentioned below to release the htemp object after adding it to the array, or else it's a big memory leak.
danielpunkass
A: 

Another common cause (not in your case, as it turns out, but generally) is forgetting to even allocate the array. If you haven't created an array yet, you're sending that count message to nil, so the result will always be 0.

Peter Hosey