Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

coredata - fetch one attribute into an array

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"]];
}
like image 807
user1046037 Avatar asked Jan 05 '13 06:01

user1046037


2 Answers

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"];
like image 110
Rahul Wakade Avatar answered Nov 12 '22 17:11

Rahul Wakade


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"];
like image 23
iDev Avatar answered Nov 12 '22 18:11

iDev