使用NSPredicate的实体自定义字段

时间:2014-01-14 12:52:34

标签: ios iphone core-data ios7

我正在尝试向实体添加自定义字段,因此我可以在使用NSFetchedResultsController获取对象时使用该字段创建谓词。该字段为full_name:

@dynamic first_name;
@dynamic last_name;

@dynamic full_name;

-(NSString *)full_name {
    [self willAccessValueForKey:@"full_name"];
    NSString *name = [NSString stringWithFormat:@"%@ %@", self.first_name, self.last_name];
    [self didAccessValueForKey:@"full_name"];
    return name;
}

然后,使用NSFetchedResultsController,我试图通过full_name获取匹配的对象:

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:[self managedObjectContext]];

[fetchRequest setEntity:entity];

NSArray *sortDescriptors = [NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"full_name" ascending:YES]];

NSMutableArray *predicateArray = [NSMutableArray array];
[predicateArray addObject:[NSPredicate predicateWithFormat:@"contact_full_name contains == '%@' ", trimmedSearchString]];

filterPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:predicateArray];

[fetchRequest setPredicate:filterPredicate];
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest                                                                                     managedObjectContext:[self managedObjectContext] sectionNameKeyPath:nil cacheName:nil];

但是,即使查询的全名存在于数据存储区中,查询也始终返回空结果。谓词为什么没有返回有效结果?

1 个答案:

答案 0 :(得分:4)

  • 您的谓词使用“contact_full_name”,而不是“full_name”。
  • "… contains == '%@'"在谓词中应为"… contains %@"
  • 核心数据提取请求只能对持久性属性进行筛选和排序,而不能对基于瞬态或基于Objective-C的自定义属性进行筛选和排序。