Search code examples
iphoneobjective-ccore-dataloadnsfetchrequest

Core Data iPhone - Loading a String


I am having troubles with understanding how to load data with Core Data. This is what I have:

Entity named 'People' Attributes of this entity named 'firstName' (string), 'lastName' (string), 'isSpecial' (boolean), 'isVerySpecial' (boolean).

I want to get the first and last name of any person who is special or very special so that I can then put those names into labels and wherever I like as I wish. I have played about with fetch requests without luck.

Any help would be much appreciated, thanks.


Solution

  • Something like this should do it:

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *weightEntity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:[[yourCoreDataManager sharedInstance] managedObjectContext]];
    [fetchRequest setEntity:weightEntity];
    [fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"isSpecial == %@ OR isVerySpecial == %@", [NSNumber numberWithBool:YES], [NSNumber numberWithBool:YES]]];
    
    NSError *error = nil;
    NSArray *result = [[yourCoreDataManager sharedInstance] managedObjectContext] executeFetchRequest:fetchRequest error:&error];
    

    And then:

    Person *person = [result objectAtIndex:0];
    NSString *lastName = person.lastName;
    NSString *firstName = person.firstName;