Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSMutableArray count always returns zero

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! :)

like image 795
John Biesnecker Avatar asked Mar 11 '09 08:03

John Biesnecker


2 Answers

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];
like image 165
Matt Ball Avatar answered Nov 03 '22 02:11

Matt Ball


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.

like image 26
Peter Hosey Avatar answered Nov 03 '22 03:11

Peter Hosey