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

iWi*_*ard 60 core-data objective-c

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

NSManagedObjectContext *context = [appDelegate managedObjectContext];

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

favorits.title = @"Some title";

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

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

Lor*_*o B 129

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

要更新特定对象,您需要设置一个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
Run Code Online (Sandbox Code Playgroud)

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

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title == %@", @"Some Title"];
[request setPredicate:predicate]; 
Run Code Online (Sandbox Code Playgroud)

在这种情况下,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
Run Code Online (Sandbox Code Playgroud)

或者如果您没有使用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
Run Code Online (Sandbox Code Playgroud)

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

  • @PavanMore您需要创建一个请求,修改您感兴趣的属性并进行保存 (3认同)

sha*_*all 11

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


Pat*_*gar 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");
    }



}
Run Code Online (Sandbox Code Playgroud)