首页 文章

带有Predicate的NSFetchRequest不返回对象

提问于
浏览
0

在我的Delegate中,我指定了以下方法来检索NSManagedObjects的NSSet:

- (NSSet *) entitiesForName : (NSString *)entityName matchingAttributes : (NSDictionary *)attributes {
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext: [NSThread isMainThread] ? managedObjectContext : bgManagedObjectContext];

NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
[fetch setEntity: entity];

NSMutableArray *subPredicates = [[NSMutableArray alloc] init];
[attributes enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
    if ([value class] == [NSString class]) {
        NSString *sValue = (NSString *)value;
        [subPredicates addObject:[NSPredicate predicateWithFormat:@"%@ == '%@'", key, [sValue stringByReplacingOccurrencesOfString:@"'" withString:@"\\'"]]];
    } else {
        [subPredicates addObject:[NSPredicate predicateWithFormat:@"%@ == %@", key, value]];
    }
}];
NSPredicate *matchAttributes = [NSCompoundPredicate andPredicateWithSubpredicates:subPredicates];
NSLog(@"matchPredicate: %@", [matchAttributes description]);
[fetch setPredicate: matchAttributes];

NSError *error;
NSSet *entities = [NSSet setWithArray: [managedObjectContext executeFetchRequest:fetch error:&error]];

if (error != nil) {
    NSLog(@"Failed to get %@ objects: %@", entityName, [error localizedDescription]);
    return nil;
}

return [entities count] > 0 ? entities : nil;
}

然后我使用我知道存在的实体启动此方法并匹配我知道具有一些相同值的属性(我检查了sqlite文件):

[self entitiesForName:@"Lecture" matchingAttributes:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:@"attending"]]

控制台输出以下内容(显示谓词):

2013-09-11 22:47:20.098 CoreDataApp[1442:907] matchPredicate: "attending" == 0

Info on the NSObject Entity:

  • 属性"attending"是BOOL(在课堂上翻译为NSNumber)
  • 此表中有许多记录(讲座实体),一半有"attending"值0和另一半1
  • 使用上面的方法-entitiesForName,它返回一个空集

Other Info:
我有另一个方法定义为检索相同的方式,但没有谓词(检索所有托管对象),这可以从同一个表 . 我用过这个,并从中分析检索到的记录也证明有些人有"attending" 0和一些1

Question:
我的-entitiesForName方法是否有问题导致该集空回来?

1 回答

  • 4

    您不应该使用 %@ 作为密钥 - 您需要使用 %K 作为密钥路径 .

    例如

    [NSPredicate predicateWithFormat:@"%K == %@", key, value]
    

    你可以在Predicate Programming Guide找到更多信息

    在您当前的情况下,密钥被视为字符串

相关问题