如何更新Core Data中的现有对象?

时间:2012-05-13 12:39:29

标签: objective-c core-data

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

NSManagedObjectContext *context = [appDelegate managedObjectContext];

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

favorits.title = @"Some title";

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

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

5 个答案:

答案 0 :(得分:128)

更新很简单,因为创建一个新的。

要更新特定对象,您需要设置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语句中。

有关详细信息,我建议您阅读核心数据编程指南和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,数据将会更新。

答案 1 :(得分:11)

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

答案 2 :(得分: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");
    }



}

答案 3 :(得分:0)

我在Objective-C中看到了一个答案,对我有帮助。我正在为Swift用户发布答案-

        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)
        }

答案 4 :(得分:-1)

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

如果要删除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)
    }
}