Reputation: 8357
I am experiencing problems with how I handle my Core Data NSManagedObjectContext
.
I can create NSManagedObject
in my NSManagedObjectContext
, but I failed to save the value.
Here's what I got:
_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];
Everything before the saving is working perfectly, I used NSLog
to verify if each value is really saved in _lesson
.
And _lesson
is sent from here:
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;
}
After debugging for two hours, I cannot find my error. Please help!
I will include my full code below:
https://www.dropbox.com/sh/eu62ie9svbbqdmm/u1hYUICfjy
That is my full source code. (I copied and pasted and created a mess. So, Dropbox!)
Thanks in advance.
Upvotes: 0
Views: 183
Reputation: 539685
This line looks suspicious:
[_managedObjectContext deleteObject:[_lessonArray objectAtIndex:index.row]];
You delete the Lesson object before passing it to the LessonViewController
, so that saving the context will delete that object from the store, and not save a (modified) object, as you probably intended.
It seems to me that you should just delete that line in your code.
ADDED: There is an error in your prepareForSegue
method: You create a new view controller with
LessonViewController* destination = [[LessonViewController alloc]init];
Instead, you must use the destination view controller of the seque:
LessonViewController *destination = [segue destinationViewController];
Upvotes: 1