核心数据的ActiveRecord
我使用这个库: https://github.com/jwang/activerecord-fetching- for-core-data
- (NSManagedObjectModel *)managedObjectModel {
if (managedObjectModel != nil) {
return managedObjectModel;
}
NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"BranchData" ofType:@"momd"];
NSURL *modelURL = [NSURL fileURLWithPath:modelPath];
managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return managedObjectModel;
}
///////
[NSManagedObjectModel setDefaultManagedObjectModel:self.managedObjectModel];
[ActiveRecordHelpers setupCoreDataStackWithStoreNamed:@"BranchData.sqlite"];
NSManagedObjectContext *context = [NSManagedObjectContext context];
[NSManagedObjectContext setDefaultContext:context];
NSLog(@"%i", [[DataBranch findAll] count]);
DataBranch *branch = [DataBranch createEntity];
NSLog(@"%i", [[DataBranch findAll] count]);
[[NSManagedObjectContext context] save];
日志打印出 0 然后是 1 但如果我重新启动我的应用程序,它不会保存到 sqlite 中。并且所有数据都会丢失 我做错了什么?
i use this library: https://github.com/jwang/activerecord-fetching-for-core-data
- (NSManagedObjectModel *)managedObjectModel {
if (managedObjectModel != nil) {
return managedObjectModel;
}
NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"BranchData" ofType:@"momd"];
NSURL *modelURL = [NSURL fileURLWithPath:modelPath];
managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return managedObjectModel;
}
///////
[NSManagedObjectModel setDefaultManagedObjectModel:self.managedObjectModel];
[ActiveRecordHelpers setupCoreDataStackWithStoreNamed:@"BranchData.sqlite"];
NSManagedObjectContext *context = [NSManagedObjectContext context];
[NSManagedObjectContext setDefaultContext:context];
NSLog(@"%i", [[DataBranch findAll] count]);
DataBranch *branch = [DataBranch createEntity];
NSLog(@"%i", [[DataBranch findAll] count]);
[[NSManagedObjectContext context] save];
It works the logs prints out 0 and then 1
But if i restart my application it is not saved into the sqlite. and all data is lost
what do i do wrong ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我混淆了需要保存到 defaultContext 的上下文,而不是上下文,因为它将创建一个新的上下文
I confused the context i needed to save to the defaultContext and not the context as it woul create a new one
您需要使用 createInContext 方法而不是 createEntity
You need to use createInContext method instead of createEntity