views:

41

answers:

3

This is probably a completely stupid question, but i'm pretty new at objective-C and programing in general. i'm trying to make an array of arrays but can't manage to make it work :

@interface ArraysAndDicts : NSObject {
 NSMutableArray * mySimpleArray;
 NSMutableArray * myComplicatedArray;
}

the implementation :

-(void)generateValueForArrayOfArrays {

    [self generateValueForArray]; 
    //this generates an array with 5 elements 'mySimpleArray'

    [myComplicatedArray addObject:mySimpleArray];

    NSMutableArray * mySecondaryArray = [[NSMutableArray alloc] init];
    [mySecondaryArray addObject:@"twoone"];
    [mySecondaryArray addObject:@"twotwo"];

    [myComplicatedArray addObject:mySecondaryArray];

(i edited out all the NSLogs for clarity)

When running my app, the console tells me :

mySecondaryArray count = 2

mySimpleArray count = 5

myComplicatedArraycount = 0

So, i know there are other ways to make multidimensional arrays, but i'd really like to know why this doesn't work. Thank you.

+2  A: 

It looks like you're never creating myComplicatedArray. This means that

[myComplicatedArray addObject:mySimpleArray];

is actually

[nil addObject:mySimpleArray];

Sending messages to nil simply has no effect in Objective-C, so nothing happens. When you ask for the count of the array, you're effectively sending [nil count], which will return 0 in your case. You can find more information about sending messages to nil here.


Also, when you're doing

NSMutableArray * mySecondaryArray = [[NSMutableArray alloc] init]; 
[mySecondaryArray addObject:@"twoone"]; 
[mySecondaryArray addObject:@"twotwo"];

mySecondaryArray will leak. You should release it, either with autorelease

NSMutableArray * mySecondaryArray = [[[NSMutableArray alloc] init] autorelease];
...

or release, whichever is appropriate.

NSMutableArray * mySecondaryArray = [[NSMutableArray alloc] init];
...
[mySecondaryArray release];
Toon Van Acker
oooh indeed. I forgot to initialize it >.< in knew that was a stupid question ;)Thanks a lot for your help. :)
Quetsche
A: 

We can't see how myComplicatedArray is initialised. Perhaps it's nil.

Graham Lee
A: 

Did you initialize myComplicatedArray somewhere?

myComplicatedArray = [[NSMutableArray alloc] init];
[self generateValueForArray];
// etc...
Alex Reynolds