Check duplicate property values of objects in NSArray

前端 未结 4 1826
北海茫月
北海茫月 2021-01-16 07:37

I have an NSArray containing objects with a size property.

How can I check if the NSArray has two objects with the same value

相关标签:
4条回答
  • 2021-01-16 08:15
    NSArray *cleanedArray = [[NSSet setWithArray:yourArraywithDuplicatesObjects ] allObjects];
    

    Use Sets this will remove all duplicates objects.Will return NSArrayNSCountedSet and use countForObject: method to find out how often each object appears how many times.

    0 讨论(0)
  • 2021-01-16 08:18

    Try this code:

    NSSet *myset = [NSSet setWithArray:[myarray valueForKey:@"size"]];
    int duplicatesCount = [myarray count] - [myset count];
    

    size here is the object property.

    0 讨论(0)
  • 2021-01-16 08:26

    Probably simplest is to sort the array based on the size field and then step through the sorted list looking for adjacent dupes.

    You could also "wrap" each object in one that exports the size as its key and use a set. But that's a lot of extra allocations.

    But if you only want to know if dupes exist, and not which ones they are, create an NSNumber for each object's size and insert the NSNumbers in a set. The final size will tell you how many dupes.

    0 讨论(0)
  • 2021-01-16 08:28

    Use NSCountedSet. then add all your objects to the counted set, and use the countForObject: method to find out how often each object appears in your array.

    You can check this link also how-to-find-duplicate-values-in-arrays

    Hope it helps you

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