01.02.2014 Views

Objective-C Fundamentals

Objective-C Fundamentals

Objective-C Fundamentals

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Building the PocketTasks application<br />

247<br />

variable of the type NSManagedObject and an init method called initWithPerson:<br />

that looks like the following listing.<br />

Listing 12.13<br />

Initializing TasksViewController with a person<br />

(TasksViewController.m)<br />

- (id)initWithPerson:(NSManagedObject *)aPerson {<br />

if ((self = [super initWithStyle:UITableViewStylePlain])) {<br />

NSManagedObjectContext *moc = [aPerson managedObjectContext];<br />

person = [aPerson retain];<br />

NSFetchRequest *request = [[NSFetchRequest alloc] init];<br />

[request setEntity:[NSEntityDescription entityForName:@"Task"<br />

inManagedObjectContext:moc]];<br />

[request setSortDescriptors:<br />

[NSArray arrayWithObject:<br />

[NSSortDescriptor sortDescriptorWithKey:@"name"<br />

ascending:YES]]];<br />

[request setPredicate:<br />

[NSPredicate predicateWithFormat:@"person == %@", person]];<br />

resultsController = [[NSFetchedResultsController alloc]<br />

initWithFetchRequest:request<br />

managedObjectContext:moc<br />

sectionNameKeyPath:nil<br />

cacheName:nil];<br />

resultsController.delegate = self;<br />

[request release];<br />

NSError *error = nil;<br />

}<br />

if (![resultsController performFetch:&error]) {<br />

NSLog(@"Error while performing fetch: %@", error);<br />

}<br />

}<br />

return self;<br />

Most of this method should look familiar, but you’ll notice one difference: the use of a<br />

predicate. What does the predicate do? It’s a filter statement, much like the WHERE<br />

clause in a SQL query. In this case you want to fetch only tasks that belong to a given<br />

person, so you create a predicate that uses the person relationship, defined in the<br />

Task entity, as a filter criteria to return only those tasks whose person relationship<br />

matches the specified person.<br />

The following listing shows the rest of the interesting methods.<br />

Listing 12.14<br />

Necessary methods in TasksViewController.m<br />

- (void)viewDidLoad {<br />

[super viewDidLoad];<br />

UIBarButtonItem *addButton =<br />

[[UIBarButtonItem alloc]<br />

Add an Add button to<br />

right navigation bar

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!