Comparing two NSManagedObjects

2020-05-30 08:43发布

问题:

I have some code that loops through an array of NSManagedObjects and stops when it finds a certain record that is stored in an instance variable. The only way I can manage to see if they are the same record (not an equivalent record, the specific record) is by comparing the URIRepresentations of the objectIDs. This surely cannot be the best way of doing it. I'm doing:

if ([[[obj1 objectID] URIRepresentation] isEqualTo: [[_obj2 objectID] URIRepresentation]]) {
  NSLog(@"Match");
}

The following code never matches even when I NSLog the objectIDs and see that they are in fact exactly the same.

if ([[obj1 objectID] isEqualTo: [_obj2 objectID]]) {
  NSLog(@"Match");
}

回答1:

The commenter is correct, isEqualTo: will not work in this case since they are different instances of NSManagedObjectID.

The way you are doing this is actually the best way, the objectID is CoreData's unique identifier for a given managed object, it's the only way to tell if two instances of NSManagedObject point to the same record in the persistent store.



回答2:

Clarification:

ImHuntingWabbits refers to isEqual:, but then advises Nick to stick with his first example, which actually uses isEqualTo:.

Per Peter Hosey's comment to the post isEqual vs isEqualTo, there is a difference and you're better off using isEqual:.

Following the present posts, I originally used isEqualTo: to compare objectID URLs, which worked fine in Cocoa, but when I moved this code over to iOS, I got warnings that "NSURL may not respond to isEqualTo." When I changed to isEqual:, the warnings went away.

So if you're following these examples, you should probably do this:

if ([[[obj1 objectID] URIRepresentation] isEqual:[[_obj2 objectID] URIRepresentation]] {
    NSLog(@"Match");
}


回答3:

-isEqual: has been implemented correctly for NSManagedObjectID in CoreData. We use collections with -contains: all the time. It seems that the original poster confused -isEqual: with -isEqualTo: The latter should not be used.