Save data to a table

Send Snippet To: Save this snippet to Code Collector Pro -- view all haxis's snippets
language: Objective-C
license: Other

Code for Snippet:

//Solution 1
@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (strong, nonatomic) IBOutlet UITextField *roleNameTextField;
- (IBAction)save:(id)sender;
- (IBAction)save:(id)sender
	//Role is a NSManagedObject
    Role *role = [NSEntityDescription insertNewObjectForEntityForName:@"Role" inManagedObjectContext:self.managedObjectContext]; = roleNameTextField.text;
    [self.managedObjectContext save:nil];  // write to database
    [self.delegate addRoleViewControllerDidSave:self];
//Solution 2 with a relationship
//AppDelegate.m - application:didFinishLaunchingWithOptions:
NSManagedObjectContext *context = [self managedObjectContext];
//Table 1
NSManagedObject *failedBankInfo = [NSEntityDescription insertNewObjectForEntityForName:@"FailedBankInfo" inManagedObjectContext:context];
[failedBankInfo setValue:@"Test Bank" forKey:@"name"];
[failedBankInfo setValue:@"Testville" forKey:@"city"];
[failedBankInfo setValue:@"Testland" forKey:@"state"];
//Table 2
NSManagedObject *failedBankDetails = [NSEntityDescription insertNewObjectForEntityForName:@"FailedBankDetails" inManagedObjectContext:context];
[failedBankDetails setValue:[NSDate date] forKey:@"closeDate"];
[failedBankDetails setValue:[NSDate date] forKey:@"updateDate"];
[failedBankDetails setValue:[NSNumber numberWithInt:12345] forKey:@"zip"];
[failedBankDetails setValue:failedBankInfo forKey:@"info"];
[failedBankInfo setValue:failedBankDetails forKey:@"details"];
//Handle Errors
NSError *error;
if (![context save:&error]) {
    NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
comments powered by Disqus


Tags: Coredata

Link to this snippet:

Download to Code Collector

To use the direct link to your snippet on either copy the html from the above section or drag the Download to Code Collector to where you would like to use it.

More Info:

Times Viewed: 700
Date Added: 2012-11-22 13:52:09
Last Modified: 0000-00-00 00:00:00

Web Analytics