Hello All&在此先感谢!
我是核心数据的菜鸟,我需要更改我的一个名为:recid的字段中的数据。
我创建了一个索引,它又是:在我的核心数据模型中recid为int 16。
我需要做的是获取记录并更改recid,我们会说5比1我将如何进行此操作?
这是我到目前为止构建的代码&在了解如何更改记录中的数据之后,我将处理我的循环。
-(void)awakeFromNib
{
NSMenu *theMenu;
statusItem = [[[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength] retain];
[statusItem setMenu:statusMenu];
[statusItem setImage:[NSImage imageNamed:@"TheJournal_16x16x32"]];
[statusItem setHighlightMode:YES];
theMenu = [[NSMenu alloc] initWithTitle:@""];
[theMenu addItemWithTitle:@"The Journal" action:@selector(showTheWindow:) keyEquivalent:@"W"];
[theMenu addItemWithTitle:@"Quit" action:@selector(terminate:) keyEquivalent:@"Q"];
[statusItem setMenu:theMenu];
[theMenu release];
NSUInteger count;
count = 0;
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
count = [prefs integerForKey:@"recid"];
NSLog(@"counter is >>>>%lu",(unsigned long)count);
[prefs setInteger:count forKey:@"recid"];
count++;
NSUserDefaults *prefs1 = [NSUserDefaults standardUserDefaults];
[prefs1 setInteger:count forKey:@"recid"];
NSLog(@"counter is >>>>%lu",(unsigned long)count);
// How I fetch the record & change the value from 5 to 1?
}
答案 0 :(得分:0)
这是一个可以帮助您的代码示例。在此示例中,YourManagedClass
核心数据实体使用UUID字符串作为唯一记录标识符。该扩展包含一个静态函数,用于获取唯一记录,设置新的recid
值,然后保存NSManagedObjectContext
。
import Foundation
import CoreData
class YourManagedClass: NSManagedObject {
@NSManaged var uuid: String?
@NSManaged var recid: NSNumber?
}
extension YourManagedClass {
static func set(recID: Int16, forObject uuid: String, `in` context: NSManagedObjectContext) {
let fetchRequest = NSFetchRequest<YourManagedClass>(entityName: "YourManagedClass")
fetchRequest.predicate = NSPredicate(format: "uuid = %@", argumentArray: [uuid])
let object: YourManagedClass
do {
let objects = try context.fetch(fetchRequest)
guard let foundObject = objects.first else {
return
}
object = foundObject
} catch {
// Handle Error
return
}
object.recid = NSNumber(value: recID)
do {
try context.save()
} catch {
// Handle Error
}
}
}
然后,您将调用此函数并引用您的NSManagedObjectContext
(此处为“上下文”):
YourManagedClass.set(recID: 15, forObject: "909455F3-C812-4399-83B4-F96A5C32A71D", in: context)