O'Reilly logo

iOS 5 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

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]; ...

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