我一直在努力将 Core Data 添加到我的 iPhone 应用程序中,并且遇到了一些非常令人沮丧的问题。当我在我的上下文中调用 save 时,保存成功返回,但是没有数据被添加到我的数据库中(我在模拟器上运行它并查看 SQLITE 文件进行检查)。
我正在使用这篇文章MYDocumentHandler
中的类来跨多个类使用一个。我在我的代码中运行如下:UIManagedDocument
AppDelegate
if (!self.document) {
[[MYDocumentHandler sharedDocumentHandler] performWithDocument:^(UIManagedDocument *document) {
self.document = document;
self.context = document.managedObjectContext;
[self loadView];
}];
}
该loadView
方法在文档返回后设置我的视图控制器。在我使用核心数据的视图控制器中,我再次使用这样的东西:
- (void)viewDidLoad
{
[super viewDidLoad];
if(!self.document){
[[MYDocumentHandler sharedDocumentHandler] performWithDocument:^(UIManagedDocument *document) {
self.document = document;
self.context = document.managedObjectContext;
[self loadAll];
}];
}
}
该loadAll
方法为视图设置所有内容的位置。当我尝试保存数据时,我使用以下内容:
for (int i = 0; i < [jsonArray count]; i++) {
NSDictionary *dictionary = [jsonArray objectAtIndex:i];
ProjectObject *tempProject = [[ProjectObject alloc] initWithDict:dictionary andETag:etag];
[tempAllProjects addObject:[Projects newProject:tempProject withContext:self.context]];
[tempProject release];
}
[self saveWithContext:self.context];
我的saveWithContext
方法如下所示:
- (BOOL) saveWithContext:(NSManagedObjectContext *)context{
NSError *error = nil;
if (context != nil) {
if ([context hasChanges] && ![context save:&error]) {
DLog(@"Unresolved error %@, %@", error, [error userInfo]);
} else{
DLog(@"save was successful");
return YES;
}
}else{
DLog(@"context is nil");
return NO;
}
}
我总是收到save was successful
消息,并且从 MYDocumentHandler 文件中得到正确的消息。不幸的是,数据根本没有进入数据库。数据肯定存储在上下文中,但不会进入数据库。有任何想法吗?
编辑: 这是我创建实体的代码:
+ (Projects *) newProject:(ProjectObject *)project withContext:(NSManagedObjectContext *)context
{
Projects *newProject = nil;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Projects"];
request.predicate = [NSPredicate predicateWithFormat:@"project_id = %@", project.project_id];
NSArray *results = [context executeFetchRequest:request error:nil];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if([results count] > 0){
newProject = [results objectAtIndex:0];
newProject.account_id = [NSString stringWithFormat:@"%@", [defaults objectForKey:@"account_id"]];
} else {
newProject = [NSEntityDescription insertNewObjectForEntityForName:@"Projects" inManagedObjectContext:context];
}
newProject.account_id = [NSString stringWithFormat:@"%@", [defaults objectForKey:@"account_id"]];
newProject.project_id = project.project_id;
newProject.name = project.name;
newProject.project_description = project.description;
newProject.updated_at = project.updated_at;
newProject.starred = project.starred;
newProject.etag = project.etag;
newProject.synced = [self hasConnection] ? [NSNumber numberWithInt:1] : [NSNumber numberWithInt:0];
return newProject;
}