我知道有过这方面的讨论,但没有一个能解决我的简单问题。
我有一个名为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?
谢谢!
答案 0 :(得分:2)
首先,使用Core Data时,不应使用外键。相反,最好使用Core Data的关系,让框架以不透明的方式处理ID。也许您正在与Web服务同步并需要跟踪ID,但您的程序逻辑实际上不应该依赖它。
其次,如果您需要一个对象,最好使用NSManagedObjectResultType
而不是NSDictionaryResultType
。您仍然可以获得不同的结果。如果您没有遇到性能问题,这是首选模式。代码也更具可读性。
您的数据结构就是这样,具有多对多关系:
Character <<--->> Episode
一集中的所有角色或具有特定角色的所有剧集都很简单。这些将是由数据模型逻辑决定的“不同”结果:
NSArray *allCharactersInEpisode = episode.characters;
NSArray *allEpisodesWithCharacter = character.episodes;
要选择所有剧集的所有字符,您只需选择所有字符即可。比“不同”的查询简单得多。