2010-10-29 44 views
2

我有一个实体(“设置”),我想在一个字段(“状态”)中获得所有的值,我正在使用coredata。任何人都可以帮助我吗?Coredata获取一个字段的所有值

+0

你试图获得“状态”所有设置对象的所有值的列表?你关心重复吗? – westsider 2010-10-29 18:35:13

回答

0

起初,u能获得值的数组:

NSFetchRequest *requestSettings = [[NSFetchRequest alloc] init]; 
[requestCodesList setEntity:[NSEntityDescription entityForName:@"Setting" inManagedObjectContext:managedObjectContext]]; 
NSArray *setting = [managedObjectContext executeFetchRequest:requestCodesList error:&error]; 
if (error) NSLog(@"Failed to executeFetchRequest to data store: %@", [error localizedDescription]); 

接着,U传输U阵列中的NSString:

ComponentsJoinedByString:构造 并返回一个NSString对象,它是 结果在 阵列的元素之间插入给定的 分隔符。

  • (的NSString *)componentsJoinedByString:(的NSString *)分离器 代码:
NSString *settingChanged = [setting componentsJoinedByString:@","]; 

和U可以使用üUI这在任何地方后(结合,setStringValue等)

1

在.h文件中声明这个: NSMutableArray * eventArray;

和.m文件

- (void)fetchRecords { 
    // Setup the fetch request 
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 

    // Define our table/entity to use 
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Settings" inManagedObjectContext:managedObjectContext]; 

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Status" ascending:YES]; 

    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; 

    [fetchRequest setSortDescriptors:sortDescriptors]; 

    [fetchRequest setEntity:entity]; 

    [fetchRequest setEntity:entity]; 

    NSError *error; 

    // Get array of results. 

    NSMutableArray *theResults = [[managedObjectContext executeFetchRequest:fetchRequest error:&error] mutableCopy]; 

    if (!theResults) { 
     // Handle the error. 
     // This is a serious error and should advise the user to restart the application 
    } 

    // Grab unique neighborhoods through NSSet. 

    NSSet *uniqueElements = [NSSet setWithArray:[theResults valueForKey:@"Status"]]; 
    // Dump NSSet uniques into new array. 

    NSMutableArray *sortedResults = [[NSMutableArray alloc] initWithArray:[uniqueElements allObjects]]; 

    for(int i = 0; i < [sortedResults count];i++) 
    { 
     NSLog(@"%d. %@", i+1, [sortedResults objectAtIndex:i]); 
    } 

    // Save our fetched data to an array 

    [self setEventArray: sortedResults]; 
}