PDA

View Full Version : Passing NSArray to a method?




neil.b
Dec 17, 2008, 07:13 AM
I'm sure I'm missing something stupidly obvious but I'm trying to pass a NSArray to the init method of my class;

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

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

And in the class;

//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
Dec 17, 2008, 07:36 AM
First, init your array like this.

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.

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

And lastly in your for loop you should probably do

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
Dec 17, 2008, 08:08 AM
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
Dec 17, 2008, 08:28 AM
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
Dec 17, 2008, 08:38 AM
:) 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. :)