如何从核心数据获取唯一字段值

如何从核心数据获取唯一字段值

本文介绍了如何从核心数据获取唯一字段值(song_type)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何从核心数据获取唯一字段值(song_type)。

I would like to know how to fetch unique field values (song_type) from core data.

我有以下代码

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

我得到以下错误


推荐答案

设置以下2个属性,你就完成了。

Set following 2 properties and you are done.

fetchRequest.returnsDistinctResults = YES;
fetchRequest.resultType = NSDictionaryResultType;

希望这有帮助。

EDIT

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

这篇关于如何从核心数据获取唯一字段值(song_type)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 11:45