Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

neil.b

macrumors member
Original poster
Nov 20, 2008
65
0
I'm sure I'm missing something stupidly obvious but I'm trying to pass a NSArray to the init method of my class;

Code:
NSArray *someStuff[3] = {@"name 1", @"name 2",  nil};

MyClass *myInstance = [[MyClass alloc] initWithStuff:*someStuff];

And in the class;

Code:
//Interface
-(id) initWithStuff:(NSArray *)array;

//Method
-(id) initWithStuff:(NSArray *)array
{
        NSString *aString;
        for (int i =0; i < 3; i++)
        {
                 aString = [array objectAtIndex:i];
                 // do some stuff with aString
        }
        return self;
}

Which causes a crash in the program in the for...loop. I know there's something fundamentally wrong but I can't see it and I can't see how to do it differently. Can anyone give me some pointers (sorry, bad pun)?
 

detz

macrumors 65816
Jun 29, 2007
1,051
0
First, init your array like this.

PHP:
NSArray *someStuff = [NSArray arrayWithObjects:@"name 1", @"name 2", nil];

NSArray is an object.

When you're passing objects to methods they are pointers already so you don't have to add the * in there.

PHP:
MyClass *myInstance = [[MyClass alloc] initWithStuff:someStuff];

And lastly in your for loop you should probably do

PHP:
for (int i =0; i < [someStuff count]; i++)

So it can accept any number of elements.

Some simple NSLog's in between this code or a breakpoint would have told you that the array was not be allocated. :p
 

neil.b

macrumors member
Original poster
Nov 20, 2008
65
0
What a dunce... :D

Thanks :)

Only problem is, I can't then define the array outside of a method or I get the error : "Initializer element is not a constant"?
 

detz

macrumors 65816
Jun 29, 2007
1,051
0
What a dunce... :D

Thanks :)

Only problem is, I can't then define the array outside of a method or I get the error : "Initializer element is not a constant"?

NSArray *myArray;

.... In init

myArray = [[NSArray alloc] init.....
 

neil.b

macrumors member
Original poster
Nov 20, 2008
65
0
:) That's what I'd done but I thought there might be a trick to defining the NSArray outside a method.

Is there no way of defining the array as a constant (outside the init method) and still be able to pass the array to my class method (and be able to index it)?

Thanks for the help, much appreciated. :)
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.