NSArray + remove item from array

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

How to remove an item from NSArray.

7条回答
  •  星月不相逢
    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;
    }
    

提交回复
热议问题