核心数据在NSManagedObjectContext中保存更改的问题

时间:2012-12-21 15:58:02

标签: core-data nsmanagedobject nsmanagedobjectcontext

我在处理核心数据NSManagedObjectContext方面遇到了问题。

我可以在NSManagedObject中创建NSManagedObjectContext,但我未能保存该值。

这是我得到的:

_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 个答案:

答案 0 :(得分:1)

这一行看起来很可疑:

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

删除 Lesson 对象,然后将其传递给LessonViewController,这样保存上下文就会从商店中删除该对象,而不是保存(修改过的)对象,就像你一样可能是有意的。

在我看来,您应该只删除代码中的那一行。


已添加:您的prepareForSegue方法出错:您使用

创建视图控制器
LessonViewController* destination = [[LessonViewController alloc]init];

相反,您必须使用seque的目标视图控制器:

LessonViewController *destination = [segue destinationViewController];
相关问题