objective-cpointersnsmutablearraymethod-declaration

Objective-C - How to implement an array of pointers in a method declaration


Ok, if you take a look at my two previous posts (Link #2 in particular), I would like to ask an additional question pertaining to the same code. In a method declaration, I am wanting to define one of the parameters as a pointer to an array of pointers, which point to feat_data. I'm sort of at a loss of where to go and what to do except to put (NSMutableArray*)featDataArray in the declaration like below and access each object via another pointer of feat_data type. BTW, sorry to be asking so many questions. I can't find some of the things like this in the book I am using or maybe I'm looking in the wrong place?

-(void)someName:(NSMutableArray*)featDataArray;

feat_data *featDataPtr = [[feat_data alloc] init];
featDataPtr = [featDataArray objectAtIndex:0];

Link #1

Link #2


Solution

  • Your declaration looks fine. "NSMutableArray*" is an appropriate type for your parameter. (Objective-C doesn't have generics so you can't declare anything about what's inside the array.)

    One problem I see in your code is that you allocate an object for no reason and then throw away the pointer (thus leaking memory).

    I don't know what it is that you are trying to do, so here are some things that you can do with an NSMutableArray:

    - (void)someName:(NSMutableArray *)featDataArray {
    
        feat_data *featDataPtr = [[feat_data alloc] init];
        [featDataArray addObject:featDataPtr]; // add an object to the end
        [featDataPtr release];
    
        feat_data *featDataPtr2 = [[feat_data alloc] init];
        [featDataArray replaceObjectAtIndex:0 withObject:featDataPtr2]; // replace an existing entry
        [featDataPtr2 release];
    
        feat_data *featDataPtr3 = [featDataArray objectAtIndex:0]; // get the element at a certain index
        // do stuff with featDataPtr3
    }