我已经在我的应用程序中集成了coreData。我在主线程中运行NSManagedObjectContext。
-(NSArray *) getResultForContext:(NSManagedObjectContext *)context
{
NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Person"];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:context];
[request setEntity:entity];
NSError *fetchError;
NSArray *allObjects = [self executeFetchRequest:request error:&fetchError];
return allObjects;
}上面的方法运行良好,但是如果我将propertiesToFetch添加到请求中,executeFetchRequest将返回一个空数组。
-(NSArray *) getResultForContext:(NSManagedObjectContext *)context
{
NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Person"];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:context];
[request setEntity:entity];
[request setResultType:NSDictionaryResultType];
[request setReturnsDistinctResults:YES];
[request setPropertiesToFetch:@[@"firstName",@"lastName"]];
NSError *fetchError;
NSArray *allObjects = [self executeFetchRequest:request error:&fetchError];
return allObjects;
}此方法返回一个空的。
这里缺少什么?
发布于 2014-02-21 01:52:55
假设(1)数据存在(即,实际上有一些Person实例要获取),并且(2)结果实际上是一个空数组,而不是nil
我知道在第一种情况下获取非空数组的唯一方法,但在第二种情况下获取空数组的唯一方法是,如果列出的属性对于所有实例都是nil。在这种情况下,没有值,因此对setReturnsDistinctResult的调用有效地过滤掉了每个结果(因为nil不被认为是不同的结果)。
对于任何现有的Person实例,如果这两个属性中的任何一个都是非nil的,那么您将得到一个非空数组。但是,如果没有要获取的属性值,则没有不同的结果,并且结果为空。
如果结果实际上是nil,而不是一个空数组,那么可以从fetchError中寻找线索。
发布于 2015-03-13 00:04:13
问题出在NSDictionaryResultType。正如bbarnhart在this post上所说,在使用resultType NSDictionaryResultType之前,您必须将上下文保存到持久存储中。
也要注意上下文persistentStoreCoordinator的声明。
https://stackoverflow.com/questions/21908322
复制相似问题