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
//.h
@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (strong, nonatomic) IBOutlet UITextField *roleNameTextField;
- (IBAction)save:(id)sender;
 
//.m
- (IBAction)save:(id)sender
{
	//Role is a NSManagedObject
    Role *role = [NSEntityDescription insertNewObjectForEntityForName:@"Role" inManagedObjectContext:self.managedObjectContext];
 
    role.name = 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"];
 
//RelationShip
[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

Info

Tags: Coredata

Link to this snippet:


Download to Code Collector

To use the direct link to your snippet on CodeCollector.net 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: 620
Date Added: 2012-11-22 13:52:09
Last Modified: 0000-00-00 00:00:00

Web Analytics