Reputation: 1596
I have a fairly large number of NSManagedObjects in an NSArray and need to check whether do any of them have the same value for a property. The obvious way is nested for loops however it will take ages to go through all of them as there are about a 1000 objects in the array.
for (NSManagedObject *object in array) {
for (NSManagedObject *secondObject in array {
if ([[object valueForKey:@"key"] isEqualTo:[secondObject valueForKey:@"key"]] &&
object != secondObject) {
NSLog(@"Sharing a property");
}
}
}
Any better way to do this? If there are 1000 objects that accounts to 1 000 000 comparisons, that might take some time.
Upvotes: 0
Views: 616
Reputation: 9006
You could use an NSDictionary
. Each entry would be made from the following pair:
key
would be equal to the selected NSManagedObject
s attributevalue
would be an NSArray
of NSManagedObject
s, that share this attribute's valueUpvotes: 4
Reputation: 64002
Get the list of key values for the objects in the array, then turn that into a set. If the size of the set is the same as that of the original array, there are no matches.
If you need to know which objects match, use a dictionary to create a multiset -- each key has an array of the objects as its value.
Creating your own keyed set class is also an option.
Upvotes: 3
Reputation: 539725
You can sort the array according to the values of that property. Then a single loop over the array is sufficient to find objects sharing the same value of the property.
Upvotes: 2