我想知道如何从核心数据中获取唯一字段值(song_type)。
我有以下代码
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Songs" inManagedObjectContext:myManagedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
[fetchRequest setPropertiesToFetch:[NSArray arrayWithObject:@"song_type"]];
[fetchRequest setEntity:entity];
NSError *aError;
NSMutableArray *fetchedResultsArray = [[myManagedObjectContext executeFetchRequest:fetchRequest error:&aError]mutableCopy];
if(! fetchedResultsArray ){
NSLog(@"EEEERRROR");
}
else {
NSLog(@"fetched %d", [fetchedResultsArray count]);
}
[fetchedResultsArray release];
[fetchRequest release];
我收到以下错误
由于未捕获的异常而终止应用 'NSInvalidArgumentException',原因:'无效的keypath song_type 传递给setPropertiesToFetch:'
答案 0 :(得分:8)
设置以下2个属性,您就完成了。
fetchRequest.returnsDistinctResults = YES;
fetchRequest.resultType = NSDictionaryResultType;
希望这有帮助。
修改强>
NSFetchRequest *fetchRequest= [[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Songs" inManagedObjectContext:myManagedObjectContext];
//Take properties dictionary
NSDictionary *entityProperties = [entity propertiesByName];
[fetchRequest setEntity:entity];
[fetchRequest setReturnsDistinctResults:YES];
[fetchRequest setPropertiesToFetch:[NSArray arrayWithObject:[entityProperties objectForKey:@"song_type"]]];
NSArray * result = [myManagedObjectContext executeFetchRequest:fetchRequest error:nil];