iOS CoreData_基本表的增加

3 篇文章 0 订阅
  1. 创建一个工程,勾选Use CoreData
  2. 创建好之后,工程会自动给我们创建好了一个.xcdatamodeld的文件,文件里就是一个sqlite的可视化界面,允许我们添加表和字段。
  3. 当我们创建好一个Student表并添加好字段后,就开始创建一个iOS 下的ManagedObjectContext的类,会自动创建好四个类,其中两个类是管理底层数据库和Model类的。
  4. 之后我们就可以对数据进行增删,查改了,本篇先讲增加。

我们使用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中了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值