目的:我想从数据库(核心数据)中获取一个属性(从实体)到数组的值.
例
实体名称=员工
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"]]; }
解决方法
你可以避免最后一个for循环,
代替,
NSMutableArray *employeeIDs = [NSMutableArray array]; for(id currentRecord in results) { [employeeIDs addObject:[currentRecord objectForKey:@"employeeID"]]; }
尝试这个,
NSMutableArray *employeeIDs = [results valueForKey:@"employeeID"];