如何从核心数据中获取唯一字段值(song_type)

时间:2012-07-03 08:16:05

标签: iphone ios core-data ios4

我想知道如何从核心数据中获取唯一字段值(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:'

1 个答案:

答案 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];