Ready to Level-Up?

This just in! If your rusty iOS skills could use some refining, or if you're just starting out and you want to level-up fast, consider signing up for our upcoming iOS Screencasts

New from iOS Rocket Surgery Swift Video Tutorials: The rapidly evolving Apple-iOS ecosystem has just been thrown into tumult with the recent introduction of the Swift Programming Language. Are you ready to finally try iOS development? Are you needing to switch from Objective-C to Swift? Sign up today for our free video courses!
(By the dear folks at Swift Tutorial Videos, a sister company)

Tuesday, October 2, 2012

Fetching a Core Data Record in iOS

// Lets start by creating a NSFetchRequest object that we will use to access the db.
// In this particular case, we have a Core Data Entity (ie. model/table) with the 
// name of 'Person'
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];

// Next, lets specify the filter criteria that we'll use to fetch our record(s)
// Here, we're basically saying "fetch people records with the last name of 'Walker'"
request.predicate = [NSPredicate predicateWithFormat:@"last_name = %@", @"Walker"];

// Next, we'll specify the order that the records should be returned into our array
// In this case, I want the order of results to be returned in last-name ascending order
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"last_name" ascending:YES];

// And now we'll just add the sort descriptor to the request
request.sortDescriptors = [NSArray arrayWithObject: sortDescriptor];

// Here, we'll set aside a reference to capture any errors that occur during a fetch    
NSError *error = nil;

// And here, we'll execute our fetch
NSArray *results = [context executeFetchRequest:request error:&error];

// Make sure we got some results
if(! results || ([results count] == 0)){
  // handle this in your particular fashion
} else {
  // Ok, now because the result set is just an array, we can grab any of the items 
     // at any index we want. But, I'm expecting there to be 1 result anyway so...

  NSObject *person = [results lastObject];

// And, yes, I could/should show you how to log the error, if any
if (error) {
  NSLog(@"Error: %@", error.localizedDescription);

About Me

Easy NSDateFormatter Tool

Save yourself some time in formatting your NSDates to NSStrings, and use the Blind NSDate app, which you can download from iTunes. There's also a website where you can format your NSDates:

Popular Posts

Designed By Seo Blogger Templates