Delete Specific Items from NSMutableArray

北战南征 提交于 2020-01-15 09:15:19

问题


I'm trying to perform the relatively simple task of deleting the items in an NSMutableArray that fit a certain criteria.

In this particular case, I'd like to delete the items where all of the following are true:

  • city: Seattle
  • state: WA
  • timestamp: more than 60 seconds old

An NSLog of my array looks like this:

array = (
            {
            city = "Seattle";
            state = "WA";
            timestamp = 1432844384;
        },
            {
            city = "Dallas";
            state ="TX";
            timestamp = 1432844415;
        },
        {
            city = "Seattle";
            state = "WA";
            timestamp = 1432845329;
        }
    )

I've tried using NSPredicate to filter the array, but I think that may be overcomplicating things. Any recommendations would be great! Thank you!


回答1:


You could get the indexes of such elements by using indexesOfObjectsPassingTest: (see docs)

NSIndexSet *indexes = [array indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
    // check if obj is matching all your criteria
}

Then remove the items using removeObjectsAtIndexes: (see docs)

[array removeObjectsAtIndexes:indexes];



回答2:


No, filtering out the items to delete and then deleting them is the right way. It iw not complicated, because obviously getting the specified items is filtering with a predicate + deleting them is deleting them. How could a solution be less complicated?

Maybe it is easier to you, to filter out the items not to delete. Simply add a NOT to your predicate.




回答3:


Here your timestamp is unique every time. So you have delete data base on timestamp.

First you have to get index of that timestamp from that array.

NSInteger index = [[array valueForKey:@"timestamp"] indexOfObject:timestamp];

After getting this index of array you have to delete data from that index.

[array removeObjectAtIndex:index];


来源:https://stackoverflow.com/questions/30516559/delete-specific-items-from-nsmutablearray

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