John’s Core Data Cheat sheet

It’s been a pretty long process for me to get working with Core Data. It’s no PHP thats for sure. In any case, below is a bunch different tasks that I was required to figure out for my development. Hopefully it helps.

Loading a specific object based on its value

    FLAppDelegate* appDelegate = [[UIApplication sharedApplication] delegate];
    NSManagedObjectContext* context = [appDelegate managedObjectContext];
    
    NSEntityDescription* enetityDescription = [NSEntityDescription entityForName:@"DataPointObject" inManagedObjectContext:context];
    NSFetchRequest* request = [[NSFetchRequest alloc] init];
    [request setEntity:enetityDescription];
    
    NSPredicate* predicate = [NSPredicate predicateWithFormat:@"(idValue = %@)", [NSNumber numberWithInteger:idValue]];
    [request setPredicate:predicate];
    NSArray* array = [context executeFetchRequest:request error:&error];

Check if Object Exists

    FLAppDelegate* appDelegate = [[UIApplication sharedApplication] delegate];
    NSManagedObjectContext* context = [appDelegate managedObjectContext];
    
    NSEntityDescription* enetityDescription = [NSEntityDescription entityForName:@"DataPointObject" inManagedObjectContext:context];
    NSFetchRequest* request = [[NSFetchRequest alloc] init];
    [request setEntity:enetityDescription];
    
    NSPredicate* predicate = [NSPredicate predicateWithFormat:@"(idValue = %@)", [NSNumber numberWithInteger:idValue]];
    [request setPredicate:predicate];

    NSError* error;
    NSInteger count = [context countForFetchRequest:request error:&error];
    if (count == NSNotFound || count == 0) {
        return NO;
    }

limit fetching request (ie load 100 objects)

    FLAppDelegate* appDelegate = [[UIApplication sharedApplication] delegate];
    NSManagedObjectContext* context = [appDelegate managedObjectContext];
    
    NSEntityDescription* enetityDescription = [NSEntityDescription entityForName:@"DataPointObject" inManagedObjectContext:context];
    NSFetchRequest* request = [[NSFetchRequest alloc] init];
    [request setEntity:enetityDescription];
    
    NSSortDescriptor* sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"idValue" ascending:NO];
    [request setSortDescriptors:@[sortDescriptor]];
    [request setFetchLimit:100];
    
    NSError* error;
    NSArray* array = [context executeFetchRequest:request error:&error];