我有一个名为People的简单实体,有2个属性,name(字符串)和birthDate(date)。
这是我的AppDelegate.h文件(只是我创建的方法,我省略了样板代码):
#import <Cocoa/Cocoa.h>
@interface AppDelegate : NSObject <NSApplicationDelegate>
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (weak) IBOutlet NSTextField *nameTextField;
@property (weak) IBOutlet NSTextField *birthDateTextField;
- (IBAction)saveButtonHasBeenClicked:(id)sender;
@end
这是AppDelegate.m文件
- (IBAction)saveButtonHasBeenClicked:(id)sender {
//NSLog(@"Name value is: %@", _nameTextField.stringValue);
//NSLog(@"Birth Date value is: %@", _birthDateTextField.stringValue);
NSError *error = nil;
if (![[self managedObjectContext] save:&error]) {
NSEntityDescription *entity = [NSEntityDescription entityForName:@"People" inManagedObjectContext:_managedObjectContext];
}
}
任何人都可以告诉我如何在单击按钮时保存用户输入的值?
答案 0 :(得分:2)
过程如下,在核心数据中获取或创建对象,然后调用save。假设您正在创建新用户,那将是:
// Create new person
Person *person = NSEntityDescription insertNewObjectForEntityForName:"Person"
inManagedObjectContext:_context];
// Apply attributes
person.name = nameField.text;
// Save new record
NSError *error = nil;
if (![[self managedObjectContext] save:&error]) {
}
如果您已将此人作为记录,则可以获取该记录而不是创建新记录。
看一下关于CoreData的一些教程:这个非常好https://www.objc.io/issues/4-core-data/full-core-data-application/