如何在Mac(osx)应用程序中保存核心数据中的文本字段值



我为osx创建了一个使用核心数据的琐碎应用程序(它不是基于文档的应用程序)

我创建了一个名为myTable的实体,里面有三个属性(myString1、myString2和myString3),它们都是字符串。

我在.xib文件中创建了3个文本字段和一个保存按钮。在AppDelegate.h中,我为文本字段创建了3个IBOutlets,为保存按钮创建了1个IBAction。

到目前为止,在AppDelegate.m中,我有以下代码:(为了简单起见,这里省略了默认代码。)

- (IBAction)saveButtonHasBeenClicked:(id)sender {
//fill the array
NSArray * myArray = [[NSArray alloc]initWithObjects:[_firstTextField stringValue],[_secondTextField stringValue], [_thirdTextField stringValue], nil];
// how to save this array in coredata?

}

如果我运行以下代码:

for (NSString *detail in myArray) {
NSLog(@"Detail is: %@",detail);
}

我可以验证数组是否已填充了文本字段的值。但是,我不确定是应该将值保存在数组中,然后将它们插入coredata中,还是应该分别插入每个文本字段值。

我知道我应该在这里做一些key:value:编码,但我不知道从哪里开始。有人可以帮我写这段代码,或者发布一些教程的链接吗?我知道如何使用NSTableView和绑定保存数据,但我找不到使用文本字段和编码的方法。

如果其他人需要解决方案,这里是:

NSManagedObject *myObject = [NSEntityDescription insertNewObjectForEntityForName:@"myTable" inManagedObjectContext:[self managedObjectContext]];
[myObject setValue:[__firstTextField stringValue] forKey:@"myString1"];
[myObject setValue:[_secondTextField stringValue] forKey:@"myString2"];
[myObject setValue:[_thirdTextField stringValue] forKey:@"myString3"];
//[self saveAction:myObject];
// above solution works also, but the solution bellow is better
NSError *myError = nil;
if (![[self managedObjectContext]save:&myError]) {
NSLog(@"Error while attempting to save the data");
}

我根本不需要这个数组,所以我必须去掉那个部分。

干杯

最新更新