当我启动应用程序并通过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];
}

最佳答案

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

- (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
}

10-05 20:26