Passing NSArray to a method?

Discussion in 'iPhone/iPad Programming' started by neil.b, Dec 17, 2008.

  1. macrumors member

    neil.b

    Joined:
    Nov 20, 2008
    #1
    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)?
     
  2. macrumors 65816

    Joined:
    Jun 29, 2007
    #2
    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 allocinitWithStuff:someStuff];
    And lastly in your for loop you should probably do

    PHP:
    for (int i =0< [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
     
  3. thread starter macrumors member

    neil.b

    Joined:
    Nov 20, 2008
    #3
    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"?
     
  4. macrumors 65816

    Joined:
    Jun 29, 2007
    #4
    NSArray *myArray;

    .... In init

    myArray = [[NSArray alloc] init.....
     
  5. thread starter macrumors member

    neil.b

    Joined:
    Nov 20, 2008
    #5
    :) 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. :)
     

Share This Page