NSArray + remove item from array

后端 未结 7 1771
-上瘾入骨i
-上瘾入骨i 2020-12-15 03:29

How to remove an item from NSArray.

相关标签:
7条回答
  • 2020-12-15 03:34

    Remove Object from NSArray with this Method:

    -(NSArray *) removeObjectFromArray:(NSArray *) array withIndex:(NSInteger) index {
        NSMutableArray *modifyableArray = [[NSMutableArray alloc] initWithArray:array];
        [modifyableArray removeObjectAtIndex:index];
        return [[NSArray alloc] initWithArray:modifyableArray];
    }
    
    0 讨论(0)
  • 2020-12-15 03:37

    Made a category like mxcl, but this is slightly faster.

    My testing shows ~15% improvement (I could be wrong, feel free to compare the two yourself).

    Basically I take the portion of the array thats in front of the object and the portion behind and combine them. Thus excluding the element.

    - (NSArray *)prefix_arrayByRemovingObject:(id)object 
    {
        if (!object) {
            return self;
        }
    
        NSUInteger indexOfObject = [self indexOfObject:object];
        NSArray *firstSubArray = [self subarrayWithRange:NSMakeRange(0, indexOfObject)];
        NSArray *secondSubArray = [self subarrayWithRange:NSMakeRange(indexOfObject + 1, self.count - indexOfObject - 1)];
        NSArray *newArray = [firstSubArray arrayByAddingObjectsFromArray:secondSubArray];
    
        return newArray;
    }
    
    0 讨论(0)
  • 2020-12-15 03:38

    As others suggested, NSMutableArray has methods to do so but sometimes you are forced to use NSArray, I'd use:

    NSArray* newArray = [oldArray subarrayWithRange:NSMakeRange(1, [oldArray count] - 1)];
    

    This way, the oldArray stays as it was but a newArray will be created with the first item removed.

    0 讨论(0)
  • 2020-12-15 03:44

    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];
    
    0 讨论(0)
  • 2020-12-15 03:44

    Here's a more functional approach using Key-Value Coding:

    @implementation NSArray (Additions)
    
    - (instancetype)arrayByRemovingObject:(id)object {
        return [self filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF != %@", object]];
    }
    
    @end
    
    0 讨论(0)
  • 2020-12-15 03:52
    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

    0 讨论(0)
提交回复
热议问题