Reputation: 21
I'm quite new to ObjC and its mutable arrays. This is driving me crazy ;-)
I do the following:
mColumns = [NSMutableArray array];
for( int i=0; i<5; i++ ) [mColumns addObject:[[MyColumn alloc] init]];
After that code my array "mColumns" contains 5 elements. But each of them is a NULL-Pointer! (Or at least that's what the debugger tells me). I already checked that the code
[[MyColumn alloc] init]
Gives me some valid objects, so I have no idea why my array gets filled with 0x0s. Can you give me a hint?
Upvotes: 2
Views: 970
Reputation: 9198
Retain your mutableArray if you want it to stick around. At the end of the current event-loop it will be automatically deallocated, as it is in the autoreleasePool.
At that point all bets are off. Your mColumns variable just points to a junk piece of memory, maybe another object, maybe half an object, maybe even you can still get the correct count or even a contained object, but at some point your app will crash.
Just a quick point, if [[mColumns objectAtIndex:x] addObject:g];
crashes your app is it [mColumns objectAtIndex:x]
that is causing the crash or is it addObject:g
?
Why not put them on separate lines and find out?
Upvotes: 2
Reputation: 18375
Hmmm. I can see one problem in your code, but not one that would cause this issue: you are adding retained objects to the array; you'll want to autorelease those first so you don't leak.
As for your actual problem, I don't know. It's impossible to fill an array with null pointers; only objects of type id
(not arbitrary pointers) can be put inside of an NSArray
/NSMutableArray
.
I know you said that you have checked -[MyColumn init]
, but it would be a good idea to check that it is producing the proper objects in this very spot.
columns = [NSMutableArray array];
for (int i = 0; i < 5; i++) {
id c = [[[MyColumn alloc] init] autorelease];
/* set a breakpoint here, and type `po c`
into the debugger to see what was created
*/
[columns addObject:c];
}
Unless -[MyColumn init]
is making some really funky objects, I can't figure out what the problem would be. I wonder whether something weird is happening to mColumns
; is it retained by anything, for instance?
Upvotes: 0
Reputation: 7463
I know you say that the objects are allocated correctly but I'd be inclined to check it. Here's the same code with more debugging:
NSMutableArray *mColumns = [NSMutableArray array];
for( int i=0; i<5; i++ ) {
MyColumn *col = [[MyColumn alloc] init];
NSLog(@"%d: %@", i, col);
[mColumns addObject:col];
[col release];
}
NSLog(@"Array has %d elements, first is %@", [mColumns count], [mColumns objectAtIndex:0]);
The problem is likely to be either (a) the object is not being created correctly, or (b) the array does have the elements and you have a different problem.
Upvotes: 0