ios - 应用重启后核心数据为空

标签 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];
}

最佳答案

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

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

关于ios - 应用重启后核心数据为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31989353/

相关文章:

ios - 我在 drawInContext 中的 NSLog 永远不会停止

ios - 强制 UIViewController 正确布局而不将其显示在屏幕上

iphone - 将 block 闭包存储为 IBAction

ios - Microsoft OneDrive 是否允许业务合作伙伴在没有 Oauth 身份验证的情况下与其连接

ios - 如何让线程A等到线程B完成,然后再继续线程A?

iphone - 如何从 ManagedObjectContext 中删除给定实体的所有对象

iphone - App 更新后 Core Data 轻量级迁移崩溃

objective-c - 更新应用程序以使用以前的双 SQLite 持久存储中的核心数据

ios - 你如何在 Xcode 中声明一个全局变量?

IOS - 控制拖动按钮不起作用