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"]];
}
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"];
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"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With