11

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

例子

实体名称 = 员工

属性 = 员工 ID

我只想将所有的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"]];
}
4

2 回答 2

23

您可以避免最后一个 for 循环,

代替,

NSMutableArray *employeeIDs = [NSMutableArray array];

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

试试这个,

NSMutableArray *employeeIDs = [results valueForKey:@"employeeID"];
于 2013-01-05T06:17:53.123 回答
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"];
于 2013-01-05T06:18:11.783 回答