我一直在努力將Core Data添加到我的iPhone應用程序中,並且我一直在遇到一些令人非常沮喪的問題。當我調用保存在我的上下文中時,保存成功返回,但是沒有數據被添加到我的數據庫中(我正在模擬器上運行它並查看要檢查的SQLITE文件)。核心數據保存成功,但數據庫中沒有數據
我使用MYDocumentHandler
類this post跨多個類使用單個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;
}
難道只是您的數據沒有被添加?如果你在saveWithContext中設置了斷點,'[context hasChanged]'是否返回true? – Clafou
嗯。你是對的。上下文沒有改變。任何方式來糾正? – coder
如果您在創建新實體的位置顯示代碼,則可能會獲得一些幫助。 – Clafou