Reputation: 11
I use this method,but not correct.
- (BOOL)checkExistByEntityName:(NSString *)entityName primaryKeyName:(NSString *)keyName primaryKey:(NSNumber *)primaryKey
{
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:managedObjectContext];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@==%@", keyName, primaryKey];
[request setEntity:entity];
[request setPredicate:predicate];
NSError *error = nil;
NSInteger count = [managedObjectContext countForFetchRequest:request error:&error];
[request release];
if (count > 0) {
return YES;
} else {
return NO;
}
}
Upvotes: 1
Views: 625
Reputation: 33428
Predicate programming guide is your friend.
The format string supports printf-style format arguments such as %x (see “Formatting String Objects”). Two important arguments are %@ and %K.
%@
is a var arg substitution for an object value—often a string, number, or date.- %K is a var arg substitution for a key path. When string variables are substituted into a format string using
%@
, they are surrounded by quotation marks. If you want to specify a dynamic property name, use%K
in the format string, as shown in the following example.
NSString *attributeName = @"firstName";
NSString *attributeValue = @"Adam";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K like %@",
attributeName, attributeValue];
So, just use
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K == %@", keyName, primaryKey];
Hope that helps.
Upvotes: 1