【问题标题】:Generic method that checks entity existence in Core Data database检查核心数据数据库中实体存在的通用方法
【发布时间】: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


    【解决方案1】:

    在下面的链接中查看动态属性名称。 http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Predicates/Articles/pCreating.html

    而不是%@,使用%K 应该可以解决您的问题

    【讨论】:

      【解决方案2】:

      你需要 == 而不是 =(我认为....)

      【讨论】:

      • 看起来在 NSPredicate 中,当涉及等号时,我们使用 SQL 约定,所以应该使用 =(奇怪的是,Core Data 并没有抱怨 ==,所以也许它们是可以互换的?)
      • 我总是使用 ==,根据 Apple 文档... NSString *predicateString = [NSString stringWithFormat: @"employeeID == %@", anID]; NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateString];
      • 我检查了@"%@ == %@" 不起作用。如果在相同的代码中我正在插入 @"fieldName == %@" 该方法有效。
      • 看看 NSExpression... 检查 Creating Predicates In Code in... developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/…
      【解决方案3】:

      您可以使用 countForFetchRequest 方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-11
        • 1970-01-01
        • 2011-10-03
        • 1970-01-01
        • 2011-11-06
        • 2012-05-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多