Search code examples
iphoneobjective-ccore-datansfetchrequest

Fetching strings (or other variables) from a CoreData fetch request?


I have Core Data setup in my app and need to fetch a bunch of items and then access the properties I choose of those fetched items. I am able to successfully fetch a bunch of results like this:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"TableInfo" inManagedObjectContext:managedObjectContext];
        [fetchRequest setEntity:entity];

        NSError *error = nil;
        NSArray *result = [managedObjectContext executeFetchRequest:fetchRequest error:&error];

This gives me an array with my results, great. Now from this how can I for example get the 'name' property from these results? In this specific circumstance I want to load an array with all of the fetched results 'name' strings.


Solution

  • If I read your question correctly, you are able to fetch your NSManagedObjects without difficulty, but would like to derive another NSArray with name properties on those managed objects?

    Then you can use the valueForKeyPath on the NSArray (extending your original code):

    NSArray *names = [result valueForKeyPath:@"name"];