NSMutableArray counter always returns zero

I'm sure I'm doing something stupid, but it drives me crazy.

I am trying to view database results, create objects from these results and add objects to NSMutableArray. I checked through NSLog calls that the data is correctly read from the database and copied to the object, but the counter for NSMutableArray always returns 0.

Here's the gist 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 am sure that this is a rookie mistake, and I hope that someone will be able to directly plant me. TIA! :)

+7
objective-c cocoa
source share
3 answers

My guess, judging by the code you provided, is that you probably aren't allocating your array properly. When creating objects, you also need to initialize them. Therefore:

 Kana *htemp = [Kana alloc]; 

Must be:

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

All objects must be initialized this way. Thus, if I am right, and you did not initialize your array, then your creation should go from this:

 NSMutableArray *hiragana = [NSMutableArray alloc]; 

:

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

For optimization reasons, you should probably also specify an initial capacity if you have an idea of ​​how many objects you can store:

 [[NSMutableArray alloc] initWithCapacity:someNumber]; 
+39
source share

Another common reason (not in your case, as it turns out, but in general) forgets to even allocate an array. If you have not created an array yet, you send this message count to nil , so the result will always be 0.

+2
source share

A few things:

  • What happens if you place an NSLog call inside a while loop? Make sure loop iterations actually occur before blaming them on the array.
  • Where do you create the hiragana array? If you do it wrong for any reason, and the array is zero, it can cause problems like this.
  • If you don't have garbage collection, be sure to make [htemp release] after adding to the loop. addObject saves and each added item will flow from the loop. Again, this only makes sense if garbage collection is disabled.

Most likely, you either did not create the array correctly, or rs does not contain what you expect from it, and therefore [rs next] does not receive a call ever (if rs is nil, for example, no iterations of this loop will be executed, and you would not have any error).

0
source share

All Articles