Tuesday, December 17, 2013

NSDictionary and Core Data

Inserting NSDictionary into core data
  //dataForDB is a NSDictionary

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dataForDB];
Record * newEntry = [NSEntityDescription insertNewObjectForEntityForName:@"Record" inManagedObjectContext:appD.managedObjectContext];
newEntry.address=data;
NSError *error;
if (![self.managedObjectContext save:&error]) {
        NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
    }

    
Fetching from core data

  NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    //Setting Entity to be Queried
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Record"
                                              inManagedObjectContext:appD.managedObjectContext];
    [fetchRequest setEntity:entity];
    NSError* error;
    // Query on managedObjectContext With Generated fetchRequest
    NSArray *fetchedRecords = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    for (Record *info in fetchedRecords) {
        NSMutableDictionary *notes = [NSKeyedUnarchiver unarchiveObjectWithData:info.address];
}

No comments: