cyclingIsBetter
cyclingIsBetter

Reputation: 17591

Get all results of a NSFetchRequest in an NSArray

In my app I do this thing to abtain all specific value from an entity

NSManagedObjectContext *context = [[self sharedAppDelegate] managedObjectContext];
NSError *error = nil;
NSFetchRequest *req = [NSFetchRequest fetchRequestWithEntityName:@"Structure"];
[req setPropertiesToFetch:@[@"id_str"]];
[req setResultType:NSDictionaryResultType];

NSArray *id_str_BD = [context executeFetchRequest:req error:&error];

int this way I obtain a NSArray of NSDictionaryies but I want directly an array of values. What's a fast way to obtain it without loops?

Upvotes: 0

Views: 638

Answers (1)

Lorenzo B
Lorenzo B

Reputation: 33428

I agree with Tom. What values?

Anyway, you can accomplish it through KVC. For example,

NSFetchRequest* fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Structure"];
[fetchRequest setPropertiesToFetch:@[@"id_str"]];

NSArray* results = [[self managedObjectContext] executeFetchRequest:fetchRequest error:nil];
NSArray* ids = [results valueForKey:@"id_str"];

NSLog(@"%@", ids);

NOTES

  • Do not pass nil for the error. ALWAYS check for a possible error (for the sake of simplicity I don't use it in this code snippet)
  • I would rename id_str to idStructure

Upvotes: 1

Related Questions