使用NSPredicate的NSFetchRequest不返回任何结果

时间:2013-05-04 05:16:54

标签: nspredicate nsfetchrequest

以下NSFetchRequest不会将任何结果返回到数组中。我怀疑NSPredicate的语法有问题。有什么想法吗?

    -(NSManagedObject*)requestTheSingleEntity:(NSString *)entityDescription ForWhichIntegerAttribute:(NSString *)attribute isEqualTo:(int)value
{
    NSFetchRequest *request = [[NSFetchRequest alloc]init];
    NSEntityDescription *e = [[model entitiesByName] objectForKey:entityDescription];

    [request setEntity:e];
    NSPredicate *p = [NSPredicate predicateWithFormat:@"(%@ == %@)", attribute, [NSNumber numberWithInt:value]];
    [request setPredicate:p];

    NSError *er;
    NSArray *results = [context executeFetchRequest:request error:&er];
    NSLog(@"the count of results = %d", [results count]);

1 个答案:

答案 0 :(得分:2)

您必须使用%K作为属性,而不是%@

NSPredicate *p = [NSPredicate predicateWithFormat:@"%K == %@", attribute, [NSNumber numberWithInt:value]];