2012-12-21 51 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:那么究竟是不是工作? –

相关问题