2

我想知道如何从核心数据中获取唯一的字段值(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”而终止应用程序,原因:“传递给 setPropertiesToFetch 的密钥路径 song_type 无效:”

4

1 回答 1

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];
于 2012-07-03T08:27:25.667 回答