我知道已经对此进行了多次讨论,但没有一个解决了我的简单问题。
我有一个名为 Character 的实体,里面有 4 列:character_id、episode_id、title、desc
可以有多个相同的 character_ids 值,但具有不同的 episode_id。
当我执行 fetch\select 时,我对整个表执行此操作,并希望通过 character_id 清楚地获取它。所以这就是我所做的:
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:moc];
[fetchRequest setEntity:entity];
// Add a sort descriptor. Mandatory.
if(sortDescriptors != nil) {
[fetchRequest setSortDescriptors:sortDescriptors];
}
fetchRequest.predicate = predicate;
// Required! Unless you set the resultType to NSDictionaryResultType, distinct can't work.
// All objects in the backing store are implicitly distinct, but two dictionaries can be duplicates.
// Since you only want distinct names, only ask for the 'name' property.
fetchRequest.resultType = NSDictionaryResultType;
fetchRequest.propertiesToFetch = [NSArray arrayWithObject:[[entity propertiesByName] objectForKey:@"title"]];
fetchRequest.returnsDistinctResults = YES;
NSArray *fetchResults = [moc executeFetchRequest:fetchRequest error:&error];
'fetchResults' 数组包含 10 行中的 3 行,这是正确的结果!
问题:数组中的任何对象都不可访问。
如果我尝试以下操作:
NSDictionary item1 = [fetchResults objectAtIndex:0];
NSString *title = [item1 objectForKey:@title"];
我得到一个例外!
我究竟做错了什么??如何将字典翻译回 NSManagedObjects?
谢谢!