13.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 = [NSNumber numberWithUnsignedInteger: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]; /* Create the fetch request first */ NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; /* Here is the entity whose contents we want to read */ NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.managedObjectContext]; ...

Get iOS 5 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.