remove object from NSArray

烈酒焚心 提交于 2019-12-07 11:41:39

问题


How can I remove an object from a reversed NSArray.

Currently I have a NSMutableArray, then I reverse it with

NSArray* reversedCalEvents = [[calEvents reverseObjectEnumerator] allObjects];

now I need to remove at item from reversedCalEvents or calEvents and automatically refresh the table the array is displayed in based on conditions. i.e.

if(someInt == someOtherInt){
    remove object at index 0
}

How can I do this? I cannot get it to work.


回答1:


You will need a mutable array in order to remove an object. Try creating reversedCalEvents with mutableCopy.

NSMutableArray *reversedCalEvents = [[calEvents reverseObjectEnumerator] allObjects] mutableCopy];

if (someInt == someOtherInt)
{
    [reversedCalEvents removeObject:object];
}



回答2:


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



回答3:


NSArray is not editable, so that you cannot modify it.

You can copy that array to NSMutableArray and remove objects from it. And finally reassign the values of the NSMutableArray to your NSArray.

From here you will get a better idea... NSArray + remove item from array




回答4:


First you should read up on the NSMutableArray class itself to familiarize yourself with it.

Second, this question should show you an easy way to remove the objects from your NSMutableArray instance.

Third, you can cause the UITableView to refresh by sending it the reloadData message.




回答5:


you can try this:-

NSMutableArray* reversedCalEvents = [[[calEvents reverseObjectEnumerator] allObjects] mutableCopy];
            [reversedCalEvents removeLastObject];


来源:https://stackoverflow.com/questions/7426570/remove-object-from-nsarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!