问题
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"]];
}
回答1:
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"];
回答2:
One way of doing it is-
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Employees"];
fetchRequest.resultType = NSDictionaryResultType;
NSError *error = nil;
NSArray *results = [self.managedObjectContext executeFetchRequest:fetchRequest
error:&error];
NSMutableArray *employeeIDs = [results valueForKey:@"employeeID"];
来源:https://stackoverflow.com/questions/14169186/coredata-fetch-one-attribute-into-an-array