检查 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;
}
}
但是看起来我编写的谓词中的字符串 @"%@ = %@"
没有正确解析。有没有什么方法可以实现所描述的功能,而无需在谓词中对实体属性进行硬编码?
I want to write generic method that checks if a given entity is in a Core Data database. I would like to have one method that works for all entities. I came up with something like this:
-(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;
}
}
However it looks like the string @"%@ = %@"
in the predicate I wrote is not parsed properly. Is there any way to implement described functionality without hardcoding entities properties in a predicate?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在下面的链接中查看动态属性名称。
http://developer.apple.com/ Library/mac/#documentation/Cocoa/Conceptual/Predicates/Articles/pCreating.html
而不是
%@
,使用%K
应该可以解决您的问题Check out dynamic property names in the link below.
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Predicates/Articles/pCreating.html
Instead of
%@
, using%K
should solve your problem你需要==而不是=(我认为......)
you need == not = (I think....)
您可以使用 countForFetchRequest 方法。
You could use the countForFetchRequest method.