O'Reilly logo

iOS 7 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

18.4. Reading Data from Core Data

Problem

You want to be able to read the contents of your entities (tables) using Core Data.

Solution

Use an instance of NSFetchRequest:

- (BOOL) createNewPersonWithFirstName:(NSString *)paramFirstName
                             lastName:(NSString *)paramLastName
                                  age:(NSUInteger)paramAge{

    BOOL result = NO;

    if ([paramFirstName length] == 0 ||
        [paramLastName length] == 0){
        NSLog(@"First and Last names are mandatory.");
        return NO;
    }

    Person *newPerson = [NSEntityDescription
                         insertNewObjectForEntityForName:@"Person"
                         inManagedObjectContext:self.managedObjectContext];

    if (newPerson == nil){
        NSLog(@"Failed to create the new person.");
        return NO;
    }

    newPerson.firstName = paramFirstName;
    newPerson.lastName = paramLastName;
    newPerson.age = @(paramAge);

    NSError *savingError = nil;

    if ([self.managedObjectContext save:&savingError]){
        return YES;
    } else {
        NSLog(@"Failed to save the new person. Error = %@", savingError);
    }

    return result;

}

- (BOOL)            application:(UIApplication *)application
  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

    [self createNewPersonWithFirstName:@"Anthony"
                              lastName:@"Robbins"
                                   age:51];

    [self createNewPersonWithFirstName:@"Richard"
                              lastName:@"Branson"
                                   age:61];

    /* Tell the request that we want to read the
     contents of the Person entity */
    /* Create the fetch request first */
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]
                                    initWithEntityName:@"Person"];

    NSError *requestError = nil;

    /* And execute the fetch request on the context */
    NSArray *persons =
    

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required