通过CoreData中的NSPredcate获取属性的所有值



这个问题听起来像个新手,但我已经完成了解决方案的所有线程,这对我来说仍然是一个问题。所以我有一个实体"LookUp",它有一个属性"descript"。现在我的问题是,我想获取属性"descript"的所有值。

到目前为止,我已经使用了所有这些查询:

[NSPredicate predicateWithFormat:@"descrip == %@",[NSNumber numberWithInt:1]];
[NSPredicate predicateWithFormat:@"descrip == %@",@"descrip"];
[NSPredicate predicateWithFormat:@"descrip == %@",[NSNumber numberWithBool:YES]];

如果我触发查询

[NSPredicate predicateWithFormat:@"descrip == %@",@"Art Gallery"];

它会返回一个数组,其中包含与"Art Gallery"相关的值。"descript"属性包含250个值,如"Art Gallery"。

请帮忙。提前谢谢。

NSPredicate用于将您的结果限制为遵守特定限制的实体-如您所说,descriptp=@"Art Gallery"将返回所有将decip属性设置为Art Gallery的实体。

在您的情况下,您不希望限制查询中的实体。只需在没有任何谓词的情况下执行查询,就会返回所有实体。现在只需在实体上循环,并将descript的所有值获取到NSMutableSetNSFmutableDictionary中,就可以获得description值的列表。

您可能想要修改获取请求,而不是谓词。请参阅苹果核心数据段中的"获取不同的值"。

NSManagedObjectContext *context = // Get the context.
NSEntityDescription *entity = [NSEntityDescription entityForName:@"LookUp" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];
[request setResultType:NSDictionaryResultType];
[request setReturnsDistinctResults:YES];
[request setPropertiesToFetch:@[@"descrip"]];
// Execute the fetch.
NSError *error;
id requestedValue = nil;
NSArray *objects = [context executeFetchRequest:request error:&error];
if (objects == nil) {
    // Handle the error.
}

您还可以设置请求

[request setResultType:NSDictionaryResultType];
[request setPropertiesToFetch:
  [NSArray arrayWithObject: @"descrip"]; 

但是,您仍然需要在results数组上循环,以便只获取descript值。

最新更新