views:

321

answers:

1

I have an NSMutableArray. It's members eventually become members of an array instance in a class. I want to put the instantiantion of NSMutable into a function and to return an array object. If I can do this, I can make some of my code easier to read. Is this possible?

Here is what I am trying to figure out.

//Definition:
function Objects (float a, float b) {
    NSMutableArray *array = [[NSMutableArray alloc] init];
    [array addObject:[NSNumber numberWithFloat:a]];
    [array addObject:[NSNumber numberWithFloat:b]];  
    //[release array]; ????????
    return array;
}

//Declaration:
 Math *operator = [[Math alloc] init];
    [operator findSum:Objects(20.0,30.0)];

My code compiles if I instantiate NSMutableArray right before I send the message to the receiver. I know I can have an array argument along with the method. What I have problem seeing is how to use a function and to replace the argument with a function call. Any help is appreciated. I am interested in the concept not in suggestions to replace the findSum method.

+4  A: 

Use autorelease to return objects you create in methods/functions.

NSMutableArray* Objects(float a, float b) {
    NSMutableArray *array = [[[NSMutableArray alloc] init] autorelease];
                     // or: [NSMutableArray array];

    [array addObject:[NSNumber numberWithFloat:a]];
    [array addObject:[NSNumber numberWithFloat:b]];  
    return array;
}

Or simply:

NSMutableArray* Objects(float a, float b) {
    return [NSMutableArray arrayWithObjects:
             [NSNumber numberWithFloat:a],
             [NSNumber numberWithFloat:b],
             nil];
}
Squeegy
This is not a valid C function declaration. Also, you need to specify your return type.
Jason Coco
yeah, just fixing that :)
Squeegy
Note: `[NSMutableArray array]` is shorthand for `[[[NSMutableArray alloc] init] autorelease]`.
mipadi
@mipadi: not sure, what you mean. It doesn't work.@squeegy: thanks!
seaworthy
@ squeegy: Does the first example add nil? or I need to add [array addObject:nil];
seaworthy
In the second example, it's providing a nil terminated list. The `nil` tells the method that there are no more objects to add. The final array has 2 objects in it. The first example doesn't use a `nil` because you are adding each object one at a time. In both examples, you end up with an array with 2 objects in it. In fact, you cannot add nil to an `NSArray` at all.
Squeegy