根据对象的属性从NSMutableArray中删除重复项

时间:2017-05-30 00:05:52

标签: ios duplicates nsmutablearray

我有这个NSMutableArray,包含一个Message对象。 Message有几个属性,其中一个是TheID。

因此,请考虑我的数组中的以下对象:

Message1.TheID = 1
Message1.title = @"whatever"

Message2.TheID = 2
Message2.title = @"doesn't matter"

Message3.TheID = 1
Message3.title = @"I don't care"

我想摆脱重复的TheIDs。

以这种方式过滤我的数组的最佳方法是什么,最终得到一个包含Message1和Message2(或Message2和Message3)的数组

我见过很多类似的问题,但没有一个解决方案似乎适用于我的情况。

感谢

1 个答案:

答案 0 :(得分:0)

您可以使用NSSet在迭代消息数组时跟踪使用的ID。只有在其数组的新数组中添加消息不在集合中。

NSMutableSet *ids = [NSMutableSet set];
NSMutableArray *newMessages = [NSMutableArray array];
for (Message *message in messagesArray) {
    if (![ids containsObject:message.theID]) {
        [ids addObject:message.TheID];
        [newMessages addObject:message];
    }
}
相关问题