简体   繁体   English

如何更新CoreData中对象的值?

[英]How to update the value of an object in CoreData?

I'm sort of new to programming with CoreData, so I have no idea how to go about doing this. 我是使用CoreData进行编程的新手,所以我不知道该怎么做。 I'm trying to update a string that's being stored in a CoreData object, but I have not the faintest idea on how to do that. 我正在尝试更新存储在CoreData对象中的字符串,但是我对如何执行此操作没有最模糊的想法。 Here's my code: 这是我的代码:

Here's where I make the new object: 这是我制作新对象的地方:

- (void)insertNewObject:(id)sender
{
     self.steakName = @"No Name";
     NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
     NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
     NSManagedObject *newManagedObject = [NSEntityDescription      insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];

     [newManagedObject setValue:self.steakName forKey:@"steakName"];

     // Save the context.
     NSError *error = nil;
     if (![context save:&error]) {
         NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
         abort();
     }
}

Here's where I want to update it: (It's being updated in a different class then where it's being made.) 这是我要对其进行更新的位置:(正在与正在创建的位置不同的类中对其进行更新。)

- (IBAction)update:(id)sender {
    MasterViewController *masterViewController = [[MasterViewController alloc] init];
    masterViewController.steakName = [self.steakNameTextField text];
    self.detailDescriptionLabel.text = masterViewController.steakName;
    NSLog(masterViewController.steakName);
}

Thank you for your help! 谢谢您的帮助! :) :)

You do it almost the same way you would without Core Data. 几乎可以像没有Core Data一样进行操作。 Keep a reference to the object as a property in the class where it's created and make whatever changes you want. 在创建对象的类中保留对该对象的引用作为属性,并进行所需的任何更改。 The only difference is, when you want the changes to persist, you save your context again. 唯一的区别是,当您希望更改继续存在时,可以再次保存上下文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM