-
CoreData 예제👻 iOS 2012. 12. 12. 10:16
// // RootViewController.m // coretest // // Created by jinwoo choi on 12. 12. 12.. // Copyright (c) 2012년 jinwoo choi. All rights reserved. // #import "RootViewController.h" #import "AppDelegate.h" #import "Person.h" @interface RootViewController () @end @implementation RootViewController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma mark - tableView delegate - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 10; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"]; if( cell == nil ){ cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"]; } cell.textLabel.text = @"test"; return cell; } #pragma mark - textField - (BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; [self saveToCoredata]; return YES; } - (void)textFieldDidEndEditing:(UITextField *)textField { [self saveToCoredata]; } #pragma mark - coredata - (void)saveToCoredata { NSError *error; AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; NSManagedObjectContext *context = appDelegate.managedObjectContext; NSManagedObjectModel *model = appDelegate.managedObjectModel; NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *dataEntity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:context]; [fetchRequest setEntity:dataEntity]; Person *obj = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:context]; obj.pid = [NSNumber numberWithInt:1]; obj.name = @"test"; [context insertObject:obj]; [context save:&error]; } @end