63

当我插入新对象时,我使用以下代码:

NSManagedObjectContext *context = [appDelegate managedObjectContext];

Favorits *favorits = [NSEntityDescription insertNewObjectForEntityForName:@"Favorits" inManagedObjectContext:context];

favorits.title = @"Some title";

NSError *error;                    
if (![context save:&error]) {
    NSLog(@"Whoops");
}

如何更新核心数据中的现有对象?

4

5 回答 5

133

更新就像创建一个新的一样简单。

要更新特定对象,您需要设置一个NSFetchRequest. 此类相当于 SQL 语言中的 SELECT 语句。

这里有一个简单的例子:

NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Favorits" inManagedObjectContext:moc]];

NSError *error = nil;
NSArray *results = [moc executeFetchRequest:request error:&error];

// error handling code

该数组results包含 sqlite 文件中包含的所有托管对象。如果要获取特定对象(或更多对象),则需要对该请求使用谓词。例如:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title == %@", @"Some Title"];
[request setPredicate:predicate]; 

在这种情况下results,包含 title 等于 的对象Some Title。设置谓词等于将 WHERE 子句放在 SQL 语句中。

有关更多信息,我建议您阅读 Core Data 编程指南和NSFecthRequest课程参考。

希望能帮助到你。

编辑(可用于更新的片段)

// maybe some check before, to be sure results is not empty
Favorits* favoritsGrabbed = [results objectAtIndex:0];    
favoritsGrabbed.title = @"My Title";

// save here the context

或者如果您没有使用NSManagedObject子类。

// maybe some check before, to be sure results is not empty
NSManagedObject* favoritsGrabbed = [results objectAtIndex:0];
[favoritsGrabbed setValue:@"My title" forKey:@"title"];

// save here the context

在这两种情况下,如果您save对上下文执行操作,数据将被更新。

于 2012-05-13T13:28:32.730 回答
11

您必须从上下文中获取对象,更改所需的属性,然后像在示例中一样保存上下文。

于 2012-05-13T13:16:56.177 回答
7

我希望这会帮助你。因为它对我有用。

 NSMutableArray *results = [[NSMutableArray alloc]init];
int flag=0;
NSPredicate *pred;
if (self.txtCourseNo.text.length > 0) {
    pred =  [NSPredicate predicateWithFormat:@"courseno CONTAINS[cd] %@", self.txtCourseNo.text];
    flag=1;
} else {
    flag=0;
    NSLog(@"Enter Corect Course number");
}

if (flag == 1) {

    NSLog(@"predicate: %@",pred);
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]initWithEntityName:@"Course"];
    [fetchRequest setPredicate:pred];
    results = [[self.context executeFetchRequest:fetchRequest error:nil] mutableCopy];


    if (results.count > 0) {
        NSManagedObject* favoritsGrabbed = [results objectAtIndex:0];
        [favoritsGrabbed setValue:self.txtCourseName.text forKey:@"coursename"];
        [self.context save:nil];
        [self showData];
    } else {
        NSLog(@"Enter Corect Course number");
    }



}
于 2015-07-25T06:28:42.320 回答
5

如果你是一个快速的程序员,这可以帮助你:

如果你想删除一个 NSManagedObject

在我的情况下,ID 是实体 STUDENT 的唯一属性

/** for deleting items */

func delete(identifier: String) {

    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "STUDENT")
    let predicate = NSPredicate(format: "ID = '\(identifier)'")
    fetchRequest.predicate = predicate
    do
    {
        let object = try context.fetch(fetchRequest)
        if object.count == 1
        {
            let objectDelete = object.first as! NSManagedObject

                 context.delete(objectDelete)
        }
    }
    catch
    {
        print(error)
    }
} 

如果要更新 NSManagedObject :

/** for updating items */
func update(identifier: String,name:String) {

    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "STUDENT")
    let predicate = NSPredicate(format: "ID = '\(identifier)'")
    fetchRequest.predicate = predicate
    do
    {
        let object = try context.fetch(fetchRequest)
        if object.count == 1
        {
            let objectUpdate = object.first as! NSManagedObject
            objectUpdate.setValue(name, forKey: "name")
            do{
                try context.save()
            }
            catch
            {
                print(error)
            }
        }
    }
    catch
    {
        print(error)
    }
}
于 2018-05-22T04:36:43.730 回答
1

I saw an answer in Objective-C which helped me. I am posting an answer for Swift users -

guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
    return
}
let updateCont = appDelegate?.persistentContainer.viewContext
let pred = NSPredicate(format: "your_Attribute_Name = %@", argumentArray : [your_Arguments])
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "your_Entity_Name")
request.predicate = pred

do {
    let resul = try updateCont?.fetch(request) as? [NSManagedObject]
    let m = resul?.first
    m?.setValue(txtName.text, forKey: "your_Attribute_Name_Whose_Value_Should_Update")
    try? updateCont?.save()
} catch let err as NSError {
    print(err)
}
于 2019-06-12T05:44:41.943 回答