coredata - fetch one attribute into an array

拟墨画扇 提交于 2020-01-29 04:40:17

问题


Aim: I would like to fetch the value of one attribute (from an entity) from the database (core data) into an array.

Example

Entity Name = Employees

Attribute = employeeID

I just want all the employeeIDs populated into an array / set.

Question

Given below is my implementation, I just feel it is kind of a round about way, I would like to know if there is a better way to do this.

Code

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Employees"];

fetchRequest.resultType = NSDictionaryResultType;

[fetchRequest setPropertiesToFetch:[NSArray arrayWithObjects:@"employeeID", nil]];

NSError *error      = nil;
NSArray *results    = [self.managedObjectContext executeFetchRequest:fetchRequest
                                                               error:&error];

NSMutableArray *employeeIDs = [NSMutableArray array];

for(id currentRecord in results)
{
    [employeeIDs addObject:[currentRecord objectForKey:@"employeeID"]];
}

回答1:


You can avoid the last for loop,

Instead of,

NSMutableArray *employeeIDs = [NSMutableArray array];

for(id currentRecord in results)
{
    [employeeIDs addObject:[currentRecord objectForKey:@"employeeID"]];
}

Try this,

NSMutableArray *employeeIDs = [results valueForKey:@"employeeID"];



回答2:


One way of doing it is-

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Employees"];
fetchRequest.resultType = NSDictionaryResultType;

NSError *error      = nil;
NSArray *results    = [self.managedObjectContext executeFetchRequest:fetchRequest
                                                               error:&error];

NSMutableArray *employeeIDs = [results valueForKey:@"employeeID"];


来源:https://stackoverflow.com/questions/14169186/coredata-fetch-one-attribute-into-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!