coredata - 将一个属性提取到数组中 [英] coredata - fetch one attribute into an array
本文介绍了coredata - 将一个属性提取到数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目标:我想从数据库(核心数据)中获取一个属性的值(来自实体)到数组中。
实体名称=员工
Attribute = employeeID
我只想将所有employeeID填充到数组/集合中。
问题 / p>
下面是我的实现,我只是觉得它是一种圆的方式,我想知道是否有一个更好的方法来做这个。 >
代码
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];
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"]];
}
解决方案
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"];
这篇关于coredata - 将一个属性提取到数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文