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, December 17, 2013

iOS Core Data NSFetchRequest Sort Descriptors Example

So, you want an NSFetchRequest to return sorted data, huh?

We're on a tear with examples on NSFetchRequests. Our last few posts covered:


Here, we're going to revisit the multiple-sort-descriptors concept with a full blown fetch example. Here's how we would go about creating an NSSortRequest against a Person entity, and returning values by last_name, age order:

+(NSArray *)getEveryoneSortedByLastName:(NSString *)lastName andAge:(int)age inManagedObjectContext:(NSManagedObjectContext *)context
{
    // Create an NSFetchRequest for the People Entity
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];

    // Fetch all People
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"1==1"];
  
    [request setPredicate:predicate];
  
    // Sort first by last_name, then by age.
    NSSortDescriptor *lastNameSort = [[NSSortDescriptor alloc] initWithKey:@"last_name" ascending:YES];
    NSSortDescriptor *ageSort = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:YES];
  
    request.sortDescriptors = [NSArray arrayWithObjects:@[lastNameSort, ageSort]];
    
    NSError *error = nil;
    NSArray *people = [context executeFetchRequest:request error:&error];
    
    return people;
}

Whew, so many NSFetchRequests posts... that's all for now.

If you found this helpful, please consider giving us a +1.




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: http://www.blindnsdate.com

Popular Posts

Designed By Seo Blogger Templates