coredata - 将一个属性提取到数组中

时间:2013-01-05 06:09:34

标签: ios core-data nsfetchrequest

目标:我想从数据库(核心数据)中获取一个属性(来自实体)的值到数组中。

示例

实体名称=员工

Attribute = employeeID

我只想将所有employeeID填充到数组/集中。

问题

鉴于以下是我的实现,我只是觉得它是一种圆形的方式,我想知道是否有更好的方法来做到这一点。

代码

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

2 个答案:

答案 0 :(得分:23)

你可以避免最后一次for循环,

而不是,

NSMutableArray *employeeIDs = [NSMutableArray array];

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

试试这个,

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

答案 1 :(得分:17)

这样做的一种方法是 -

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

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

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