iosobjective-ccore-datansfetchrequestnsentitydescription

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?


Solution

  • 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