使用Core Data保存对现有实体的更改

时间:2011-08-04 01:36:26

标签: objective-c core-data

我有一个笔记应用程序,我试图在Apple Notes应用程序后建模。我有一个NotesTableViewController,它显示现有的笔记,并有一个按钮来添加新笔记。触摸添加新笔记按钮时,NoteViewController被推入堆栈,用户可以键入他们的笔记。按下后退按钮时,将调用下面的saveNote方法。这部分工作正常。当我尝试将更改保存到现有注释时,问题就出现了。我从NotesTableViewController中选择一个音符,NoteViewController出现,我做了一些更改并完成后按下后退按钮。这只是创建一个新笔记而不是更新现有笔记。如何修改以下方法来实现此目的?

- (void) saveNote
{
    NSLog(@"Save");
    NSManagedObjectContext *context = self.managedObjectContext;

    NSEntityDescription *entity = [NSEntityDescription 
                                   entityForName:@"Note"
                                   inManagedObjectContext:context];

    Note *newManagedObject = 
    [NSEntityDescription insertNewObjectForEntityForName:[entity name] 
                                  inManagedObjectContext:context];

    // If appropriate, configure the new managed object.
    if ([textView hasText])
    {
        [newManagedObject setValue:[NSDate date] forKey:@"timeStamp"];
        [newManagedObject setValue:self.title forKey:@"noteName"];
        [newManagedObject setValue:textView.text forKey:@"noteText"];
        //NSLog(@"%@", textView.text);
    }

    NSError *error = nil;
    if (![context save:&error]) {
        /*
         Replace this implementation with code to handle the error 
         appropriately.

         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    [self.navigationController popViewControllerAnimated:YES];
}

1 个答案:

答案 0 :(得分:1)

搞定了。下面是新的saveNote方法。此外,在NotesTableViewController的tableView:didSelectRowAtIndexPath中:我没有将NoteViewController的managedObject设置为所选的managedObject。

Note *managedNoteObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
//  Where detailViewController is an instance of NoteViewController.
detailViewController.managedObject = managedNoteObject;


- (void) saveNote
{
    NSLog(@"Save");

    if([textView hasText])
    {
        [managedObject setValue:[NSDate date] forKey:@"timeStamp"];
        NSLog(@"timeStamp: %@", [managedObject valueForKey:@"timeStamp"]);
        [managedObject setValue:self.title forKey:@"noteName"];
        NSLog(@"NoteName: %@", [managedObject valueForKey:@"noteName"]);
        [managedObject setValue:textView.text forKey:@"noteText"];
        NSLog(@"%@", managedObject);
    }

    NSError *error = nil;
    if (![self.managedObjectContext save:&error]) {
        /*
         Replace this implementation with code to handle the error 
         appropriately.

         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    [self.navigationController popViewControllerAnimated:YES];
}