- 创建一个工程,勾选Use CoreData
- 创建好之后,工程会自动给我们创建好了一个.xcdatamodeld的文件,文件里就是一个sqlite的可视化界面,允许我们添加表和字段。
- 当我们创建好一个Student表并添加好字段后,就开始创建一个iOS 下的ManagedObjectContext的类,会自动创建好四个类,其中两个类是管理底层数据库和Model类的。
- 之后我们就可以对数据进行增删,查改了,本篇先讲增加。
我们使用StoryBoard,创建一个
然后在ViewController中添加属性关联控件。
@interface ViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *nameTextField;
@property (weak, nonatomic) IBOutlet UITextField *ageTextField;
@property (weak, nonatomic) IBOutlet UITextField *genderTextField;
@property (weak, nonatomic) IBOutlet UITextField *addressTextField;
@property (weak, nonatomic) IBOutlet UITextField *deletedNameTextField;
@property(nonatomic,strong) AppDelegate *appDelegate;
@property(nonatomic,strong) NSMutableArray *allStudent;
@end
在ViewDidLoad中`- (void)viewDidLoad {
[super viewDidLoad];
//获取AppDelegate
self.appDelegate = [UIApplication sharedApplication].delegate;
self.addressTextField.delegate = self;
self.deletedNameTextField.delegate = self;
}`
//添加
- (IBAction)addAction:(UIButton *)sender {
//获得页面上的数据
NSString *name = self.nameTextField.text;
NSNumber *age = [NSNumber numberWithInt:self.ageTextField.text.intValue];
NSString *gender = self.genderTextField.text;
NSString *address = self.addressTextField.text;
//跟数据库中的表名创建一个实体描述对象。
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:_appDelegate.managedObjectContext];
//加入到被管理对象上下文中。
Student *student_01 = [[Student alloc]initWithEntity:entityDescription insertIntoManagedObjectContext:_appDelegate.managedObjectContext];
//给实体对象的各个属性赋值
student_01.name = name;
student_01.age = age;
student_01.gender = gender;
student_01.address = address;
//保存并更新数据
[_appDelegate saveContext];
}
这样就已经把数据添加到CoreData中了。