coredata – 获取一个属性到一个数组中

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

实体名称=员工

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

你可以避免最后的循环,

代替,

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

尝试这个,

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

一种做法是 –

 NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Employees"]; fetchRequest.resultType = NSDictionaryResultType; NSError *error = nil; NSArray *results = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error]; NSMutableArray *employeeIDs = [results valueForKey:@"employeeID"];