Below is my find-or-create code:
+ (id)checkIfEntity:(NSString *)entityName
withIDValue:(NSString *)entityIDValue
forIDKey:(NSString *)entityIDKey
existsInContext:(NSManagedObjectContext *)context
{
// Create fetch request
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setReturnsObjectsAsFaults:NO];
// Fetch messages data
NSEntityDescription *description = [NSEntityDescription entityForName:entityName inManagedObjectContext:context];
[request setEntity:description];
// Only include objects that exist (i.e. entityIDKey and entityIDValue's must exist)
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@=%@", entityIDKey, entityIDValue];
[request setPredicate:predicate];
// Execute request that returns array of dashboardEntrys
NSArray *array = [context executeFetchRequest:request error:nil];
if ( [array count] ) {
NSLog(@"%@ = %@ DOES EXIST", entityIDKey, entityIDValue);
return [array objectAtIndex:0];
}
NSLog(@"%@ = %@ DOES NOT EXIST", entityIDKey, entityIDValue);
return [NSEntityDescription insertNewObjectForEntityForName:entityName inManagedObjectContext:context];
}
Please ignore the fact that I’m not employing best-practices by having two return statements – I will this before pushing my code to production.
It works by passing an NSManagedObject entity with entityName, and has an NSPredicate that checks if there’s an entityIDKey with value entityIDValue; entityIDKey = entityIDValue. I’ve also tried with using ==.
Regardless which comparison method I use, the if ( [array count] ) method is never hit, so the second NSLog statement always gets output, delineating that an object that I know exists in my Core Data store doesn’t actually exist. Therefore, I end up with many duplicate entries when I go to display the contents of my store.
Is my NSPredicate statement correct?
`NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@=%@", entityIDKey, entityIDValue];`
where entityIDKey = @"userID" and entityIDvalue = @"1234567890"
Thanks!
Yup, the problem was definitely the predicate.
The predicate argument should have been:
%K == %@not
%@ = %@