2012-12-21 52 views
0

我遇到了如何處理我的核心數據NSManagedObjectContext的問題。在NSManagedObjectContext中保存更改的核心數據問題

我可以在我的NSManagedObjectContext中創建NSManagedObject,但我未能保存該值。

這裏是我的了:保存工作之前完全

_lesson.title = _titleField.text; 

int priority = [_priorityField.text intValue]; 
int difficulty = [_difficultyField.text intValue]; 
int time = [_timeField.text intValue]; 
int sortIndex = 0; 
if (time == 0) 
{ 
    sortIndex = 101; 
} 
else 
{ 
    sortIndex = priority * (difficulty/time); 
} 
_lesson.priority = [NSNumber numberWithInt:priority]; 
_lesson.difficulty = [NSNumber numberWithInt:difficulty]; 
_lesson.time = [NSNumber numberWithInt:time]; 
_lesson.sortIndex = [NSNumber numberWithInt:sortIndex]; 
NSError* error = nil; 
[[(AppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext] save:&error]; 

的一切,我以前NSLog,以驗證是否每個值真的是保存在_lesson

而且_lesson就是從這裏發出:

if ([[segue identifier] isEqualToString:@"addLesson"]) 
{ 
    LessonViewController* destination = [[LessonViewController alloc]init]; 
    Lesson* lesson = (Lesson*)[NSEntityDescription insertNewObjectForEntityForName:@"Lesson" inManagedObjectContext:_managedObjectContext]; 
    destination.lesson = lesson; 
} 
else if ([[segue identifier] isEqualToString:@"editLesson"]) 
{ 
    LessonViewController* destination = [[LessonViewController alloc]init]; 
    NSIndexPath* index = [_tableView indexPathForCell:(UITableViewCell*)sender]; 
    [_managedObjectContext deleteObject:[_lessonArray objectAtIndex:index.row]]; 
    Lesson* lesson = (Lesson*)[_lessonArray objectAtIndex:index.row]; 
    destination.lesson = lesson; 
} 

的調試兩小時後,我找不到我的錯誤。請幫忙!

我將包括下面我完整的代碼:

https://www.dropbox.com/sh/eu62ie9svbbqdmm/u1hYUICfjy

這是我的完整源代碼。 (我複製粘貼並創建了一個混亂,所以,Dropbox!)

在此先感謝。

回答

1

這行看起來可疑:

[_managedObjectContext deleteObject:[_lessonArray objectAtIndex:index.row]]; 

你把它傳遞給LessonViewController,從而節省了上下文將刪除該商店對象之前刪除對象,而不是保存(修改)對象,你可能打算。

在我看來,你應該只是刪除代碼中的那一行。


新增:有一個在你的prepareForSegue方法的錯誤:你創建

LessonViewController* destination = [[LessonViewController alloc]init]; 

一個視圖控制器相反,你必須使用塞克的目的地視圖控制器:

LessonViewController *destination = [segue destinationViewController]; 
+0

這是來自以前處理編輯方法的一行代碼。在甚至刪除之前,我真的想抽出一點時間對自己說:「哇,你真傻。」我將刪除該行並重試。感謝您閱讀長碼。 –

+0

在意識到我很愚蠢之後。另一個問題打擊了我。數據沒有被編輯,所以該行現在不會真正執行,因爲我還沒有真正嘗試編輯任何東西。但是你是對的,那行應該被刪除。 –

+0

@ShaneHsu:那麼究竟是不是工作? –

相關問題