应用重启后核心数据为空

时间:2015-08-13 13:15:39

标签: ios objective-c core-data

当我启动应用并通过Core DataUITextField输入一些数据时,它们会在UITableView中正确显示。问题是当我重新启动应用程序时,Core Data中的所有数据都将丢失...这是我的代码。

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;


- (void)viewDidLoad {
    [super viewDidLoad];
    AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
    _managedObjectContext = [appDelegate managedObjectContext];
    _managedObjectModel = [appDelegate managedObjectModel];
    _persistentStoreCoordinator = [appDelegate persistentStoreCoordinator];

}


- (IBAction)saveButtonPressed:(id)sender {
    Truck *truck = [NSEntityDescription insertNewObjectForEntityForName:@"Truck" inManagedObjectContext:_managedObjectContext];
    [truck setModel:self.tField.text];
}

1 个答案:

答案 0 :(得分:3)

创建卡车对象后,必须保存上下文,以便将其写入数据库。

- (IBAction)saveButtonPressed:(id)sender {
    Truck *truck = [NSEntityDescription insertNewObjectForEntityForName:@"Truck" inManagedObjectContext:_managedObjectContext];
    [truck setModel:self.tField.text];
    [_managedObjectContext save:nil];  // you should provide an NSError object
}