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

NSManagedObjectContext *context = [appDelegate managedObjectContext];

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

favorits.title = @"Some title";

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

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

推荐答案

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

要更新特定对象,需要设置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类参考资料.

  • 一百

  • 一百

希望有帮助.

EDIT(可用于更新的代码段)

// 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,数据将被更新.

Objective-c相关问答推荐

将 NSInteger 转换为 NSIndexpath

导航回上一个视图控制器

UITextField secureTextEntry 带有自定义字体的项目符号?

ios 使用 AVFramework 捕获图像

为什么在目标 c 的静态上下文中允许 self

在 Interface Builder 中设计 UITableView 的section header

setFont 已弃用?

滚动 NSScrollView 时的回调?

将长格式的 NSString 拆分为多行

混合 Objective-C 和 C++

didReceiveRemoteNotification:当应用程序处于后台并且未连接到Xcode时未调用fetchCompletionHandler

OSStatus 错误代码 -34018

arc4random 和 arc4random_uniform 有什么区别?

自定义导航栏样式 - iOS

仅在 UIView 顶部的圆角

如何检测 NSString 是否为空?

cellForRowAtIndexPath 是如何工作的?

command/usr/bin/codedesign 失败,退出代码 1-代码符号错误

带有 UIImage 的 UIBarButtonItem 始终着色 iOS 7

Objective-C in,out,inout,byref,byval, .. 等等.这些是什么?