Text Size
Tuesday, October 21, 2014

13.02.13

Creating a Managed Object

How to create a Managed Object in Objective-c

Creating new item manually with code
- (IBAction)createObject:(id)sender { // Button

...
    NSManagedObject *myMO = [NSEntityDescription
                             insertNewObjectForEntityForName:@"Course"
                             inManagedObjectContext:[self managedObjectContext]];
    
    [myMO setValue:@"Core Data for iOS and OS X" forKey:@"title"]; // Set the Title
    [myMO setValue:[NSDate date] forKey:@"releaseDate"]; // Set the current Date
...

Storing the information, this is in AppDelegate.m
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender

...
    NSError *error = nil;
    if (![[self managedObjectContext] save:&error]) {  // <-- Save to Core Data if did not save show error in NSLog
       NSLog(@"Error %@",error);
    }
...

Creating Object using Elements

...
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd MMM yyyy"];
    
    // First Course object
    Course *first = (Course *) [NSEntityDescription
                                insertNewObjectForEntityForName:@"Course"
                                inManagedObjectContext:[self managedObjectContext]];
    first.title = @"Core Data for iOS and OS X";
    first.releaseDate = [dateFormatter dateFromString:@"13 Feb 2013"];
...

Course must exist in {filename}.xcdatamodeld and your should have an object Course.h and Course.m file, to create Click on Editor->Create Managed Subclass

Fields of Course are Title and as String and releaseData as date

To get the data you use a Fetch Request as follows

...
    // Create fetch Request
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Course" inManagedObjectContext:[self managedObjectContext]];
    [fetchRequest setEntity:entity];

    // Where
//    NSPredicate *where = [NSPredicate predicateWithFormat:@"author==[c] 'Mike Zriel'"]; // not case sensitive equals
//    NSPredicate *where = [NSPredicate predicateWithFormat:@"author LIKE[cd] '*vid*'"]; // not case sensitve and accents LIKE * is wildcard
    NSPredicate *where = [NSPredicate predicateWithFormat:@"author LIKE[c] 'Mike*' AND releaseDate < %@", [NSDate date]]; // not case sensitive and with parameter Date in this case
   [fetchRequest setPredicate:where];


    // Sort like order by in sql
    NSSortDescriptor *sortDate = [[NSSortDescriptor alloc] initWithKey:@"releaseDate" ascending:YES];
    NSSortDescriptor *sortTitle = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES];

    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortTitle,sortDate,nil];
    [fetchRequest setSortDescriptors:sortDescriptors];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [[self managedObjectContext] executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"Error: %@",error);
    }
    // Log the result for testing
    for( Course *c in fetchedObjects) { // for each loop
        NSLog(@"Title: %@ Author %@ Date: %@",c.title,c.author,c.releaseDate);
        
    }

...

You get get a Sample of this code in the Code Snippet Library {}, search for "core data"

Add comment


Security code
Refresh

Copyright © 2014 by Mike Zriel - Zriel.com