NSArray + remove item from array
How to remove an item from NSArray.
Solution 1:
NSArray is not mutable, that is, you cannot modify it. You should take a look at NSMutableArray. Check out the "Removing Objects" section, you'll find there many functions that allow you to remove items:
[anArray removeObjectAtIndex: index];
[anArray removeObject: item];
[anArray removeLastObject];
Solution 2:
NSMutableArray *arrayThatYouCanRemoveObjects = [NSMutableArray arrayWithArray:your_array];
[arrayThatYouCanRemoveObjects removeObjectAtIndex:your_object_index];
[your_array release];
your_array = [[NSArray arrayWithArray: arrayThatYouCanRemoveObjects] retain];
that's about it
if you dont own your_array(i.e it's autoreleased) remove the release & retain messages
Solution 3:
This category may be to your taste. But! Be frugal with its usage; since we are converting to a NSMutableArray and back again, it's not at all efficient.
@implementation NSArray (mxcl)
- (NSArray *)arrayByRemovingObject:(id)obj
{
if (!obj) return [self copy]; // copy because all array* methods return new arrays
NSMutableArray *mutableArray = [NSMutableArray arrayWithArray:self];
[mutableArray removeObject:obj];
return [NSArray arrayWithArray:mutableArray];
}
@end