views:

60

answers:

1

Hello, how would you copy the last object of a array and then add the object to some array. So in other words i want to take the last object of someArray and copy that lastObject to someArray2.

Thanks,

-David

A: 
NSArray *firstArray = [[NSArray alloc] init];
... populate firstArray ...
NSArray *secondArray = [NSArray arrayWithObject:[firstArray lastObject]];

or

NSArray *firstArray = [[NSArray alloc] init];
... populate firstArray ...
NSMutableArray *secondArray = [NSMutableArray alloc] init];
[secondArray addObject:[firstArray lastObject]];

or

NSArray *firstArray = [[NSArray alloc] init];
... populate firstArray ...
NSArray *secondArray = [[NSArray alloc] init];
NSArray *thirdArray = [secondArray arrayByAddingObject:[firstArray lastObject]];

Make sure everything is released as you now own all these references.

Edit: If you want a COPY everywhere there's [firstArray lastObject] change it to [[[firstArray lastObject] copy] autorelease] (thanks tc)

Matt S
Re: your third snippet: `arrayByAddingObject` gives you a *new* autoreleased array that is a copy of your original `secondArray`. Since you assign it back to the `secondArray` pointer, you've lost track of the original memory obtained via alloc/init. It's a leak!
Matt B.
Bad Matt! The edit should be `NSArray *thirdARray = [secondArray arrayBy...`. Thanks for clearing that up for me. Awesome name btw!
Matt S
You're still leaking in the third one when you lose the original array created with `NSArray *secondArray = [[NSArray alloc] init]`.
Chuck
I didn't do releases in any of the previous methods as they were assumed. In the final case the edit means that the pointer to secondArray is not lost and can still be released unless I'm missing something.
Matt S
You mean `[[[firstArray lastObject] copy] autorelease]`.
tc.