我想知道如何从核心数据中获取唯一字段值(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];
我收到以下错误
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid keypath song_type passed to setPropertiesToFetch:'
最佳答案
设置以下 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];
关于iphone - 如何从核心数据中获取唯一字段值(song_type),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11306950/