【发布时间】:2011-05-23 10:52:36
【问题描述】:
我想编写通用方法来检查给定实体是否在 Core Data 数据库中。我想要一种适用于所有实体的方法。我想出了这样的事情:
-(BOOL)checkIfExistsEntity:(NSString *)entityName withFieldName:(NSString *)fieldName andFieldValue:(NSString *)value{
NSManagedObjectContext *managedObjectContext = [(FGuideAppDelegate *) [[UIApplication sharedApplication] delegate] managedObjectContext];
NSEntityDescription *selectEntityDescription = [NSEntityDescription
entityForName:entityName inManagedObjectContext:managedObjectContext];
NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease];
[fetchRequest setEntity:selectEntityDescription];
NSPredicate *whereForFetch = [NSPredicate predicateWithFormat:@"%@ = %@",fieldName, value];
[fetchRequest setPredicate:whereForFetch];
NSError *error = nil;
NSArray *array = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (array != nil && [array count] > 0){
return YES;
}else {
return NO;
}
}
但是看起来我写的谓词中的字符串@"%@ = %@" 没有正确解析。有什么方法可以实现所描述的功能,而无需在谓词中硬编码实体属性?
【问题讨论】:
标签: iphone objective-c ios core-data