iOS CoreData实现数据存储(二)

前言

数据是移动端的重点关注对象,其中有一条就是数据存储。CoreData是苹果出的数据存储和持久化技术,面向对象进行数据相关存储。感兴趣的可以看下面几篇文章。
1. iOS CoreData(一)


实现效果

我们先看下边的gif图,主要就是实现数据的新增,已有数据的删除和修改。

  1. 在数据展示界面导航点击“新增”按钮,到下一个界面,填写数据新增数据,数据的每一项不能为空。返回数据展示界面新增一条数据。
  2. 点击数据展示界面的一条数据,来到数据修删界面,可以对已有的某一条数据进行修改和删除。返回数据展示界面会发现原有数据实现了删除或者修改。
CoreDataDemo.gif

代码实现

前面已经有了项目的需求,下面我们直接来代码实现,就不讲过多的理论了。我们先看一下工程的项目框架的搭建。

项目DEMO文件概览

下面我就分着文件给大家说

//这里主要就是对window根视图进行初始化,基本都会,就不多啰嗦了,为了整体看着全面点我也都粘贴出来了,大神务笑,哈哈。
1. AppDelegate.m
#import "AppDelegate.h"
#import "DDDataDisplayVC.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    DDDataDisplayVC *displayVC = [[DDDataDisplayVC alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:displayVC];
    self.window.rootViewController = nav;
    [self.window makeKeyAndVisible];
    return YES;
}


// 数据展示的实现
2. DDDataDisplayVC.h
#import <UIKit/UIKit.h>

@interface DDDataDisplayVC : UIViewController

@end

DDDataDisplayVC.m 文件
#import "DDDataDisplayVC.h"
#import "DDDataSetVC.h"
#import "DDCoreDataManager.h"
#import "PersonEntity.h"
#import "DDDataDisplayCell.h"

#define kDDDataDisplayVCCellReuseIdentify   (@"kDDDataDisplayVCCellReuseIdentify")

@interface DDDataDisplayVC () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) NSMutableArray *dataArrM;
@property (nonatomic, strong) DDCoreDataManager *dataManager;
@property (nonatomic, strong) UITableView *tableView;

@end

@implementation DDDataDisplayVC

#pragma mark - Override Base Function

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = @"数据展示";
    self.dataArrM = [NSMutableArray array];
    self.dataManager = [DDCoreDataManager shareCoreDataManager];
    self.tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView setSeparatorColor:[UIColor redColor]];
    self.tableView.rowHeight = 80.0;
    [self.tableView registerClass:[DDDataDisplayCell class] forCellReuseIdentifier:kDDDataDisplayVCCellReuseIdentify];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"新增" style:UIBarButtonItemStylePlain target:self action:@selector(addData)];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"PersonEntity" inManagedObjectContext:self.dataManager.manageObjectContext];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:YES];
    NSArray *sortArr = [NSArray arrayWithObjects:sortDescriptor, nil];
    
    [request setEntity:entityDescription];
    [request setSortDescriptors:sortArr];
    
    NSError *error = nil;
    NSArray *fetchResults = [self.dataManager.manageObjectContext executeFetchRequest:request error:&error];
    if (error) {
        NSLog(@"error --- %@ --- %@",error,[error userInfo]);
    }
    [self.dataArrM removeAllObjects];
    [self.dataArrM addObjectsFromArray:fetchResults];
    [self.tableView reloadData];

}

#pragma mark - Action/Event

- (void)addData
{
    DDDataSetVC *dataSetVC = [[DDDataSetVC alloc] init];
    dataSetVC.title = @"数据增加";
    dataSetVC.type = DDDataSetVCTypeADD;
    [self.navigationController pushViewController:dataSetVC animated:NO];

}

#pragma mark - UITableViewDelegate & UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArrM.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DDDataDisplayCell *cell = [tableView dequeueReusableCellWithIdentifier:kDDDataDisplayVCCellReuseIdentify forIndexPath:indexPath];
    if (!cell) {
        cell = [[DDDataDisplayCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:kDDDataDisplayVCCellReuseIdentify];
    }
    cell.personEntity = self.dataArrM[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    PersonEntity *personEntity = [self.dataArrM objectAtIndex:indexPath.row];
    DDDataSetVC *dataSetVC = [[DDDataSetVC alloc] init];
    dataSetVC.type = DDDataSetVCTypeChange;
    dataSetVC.title = @"数据修删";
    dataSetVC.personEntity = personEntity;
    [self.navigationController pushViewController:dataSetVC animated:NO];
}

@end

// 自定义cell的实现
3. DDDataDisplayCell.h
#import <UIKit/UIKit.h>
#import "PersonEntity.h"

@interface DDDataDisplayCell : UITableViewCell

@property (nonatomic, strong) PersonEntity *personEntity;

@end
DDDataDisplayCell.m 文件中

#import "DDDataDisplayCell.h"

#define kDDDataDisplayCellLabelTextColor  ([UIColor blueColor])
#define kDDDataDisplayCellScreenWidth     ([UIScreen mainScreen].bounds.size.width * 0.5)

#define kDDDataDisplayCellLabelWidth            (100.0)
#define kDDDataDisplayCellLabelHeight           (20.0)
#define kDDDataDisplayCellLabelLeftMargin       (10.0)
#define kDDDataDisplayCellLabelTopMargin        (8.0)


@interface DDDataDisplayCell ()

@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UILabel *genderLabel;
@property (nonatomic, strong) UILabel *locationLabel;
@property (nonatomic, strong) UILabel *ageLabel;


@end


@implementation DDDataDisplayCell

#pragma mark - Override Base Function

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self setupUI];
    }

    return self;
}


#pragma mark - Object Private Function

- (void)setupUI
{
    //姓名
    UILabel *nameLabel = [[UILabel alloc] init];
    nameLabel.textColor = kDDDataDisplayCellLabelTextColor;
    [self.contentView addSubview:nameLabel];
    
    //年龄
    UILabel *ageLabel = [[UILabel alloc] init];
    ageLabel.textColor = kDDDataDisplayCellLabelTextColor;
    [self.contentView addSubview:ageLabel];

    //性别
    UILabel *genderLabel = [[UILabel alloc] init];
    genderLabel.textColor = kDDDataDisplayCellLabelTextColor;
    [self.contentView addSubview:genderLabel];
    
    //地区
    UILabel *locationLabel = [[UILabel alloc] init];
    locationLabel.textColor = kDDDataDisplayCellLabelTextColor;
    [self.contentView addSubview:locationLabel];
    
    self.nameLabel = nameLabel;
    self.ageLabel = ageLabel;
    self.genderLabel = genderLabel;
    self.locationLabel = locationLabel;

}

- (void)layoutSubviews
{
    
    //姓名
    self.nameLabel.frame = CGRectMake(kDDDataDisplayCellLabelLeftMargin, kDDDataDisplayCellLabelTopMargin, kDDDataDisplayCellLabelWidth, kDDDataDisplayCellLabelHeight);
    [self.nameLabel sizeToFit];
    
    //年龄
    self.ageLabel.frame = CGRectMake(kDDDataDisplayCellScreenWidth, CGRectGetMinY(self.nameLabel.frame), kDDDataDisplayCellLabelWidth, kDDDataDisplayCellLabelHeight);
    [self.ageLabel sizeToFit];
    
    //性别
    self.genderLabel.frame = CGRectMake(CGRectGetMinX(self.nameLabel.frame), CGRectGetMaxY(self.nameLabel.frame) + kDDDataDisplayCellLabelTopMargin, kDDDataDisplayCellLabelWidth, kDDDataDisplayCellLabelHeight);
    [self.genderLabel sizeToFit];
    
    //位置
    self.locationLabel.frame = CGRectMake(CGRectGetMinX(self.ageLabel.frame), CGRectGetMinY(self.genderLabel.frame), kDDDataDisplayCellLabelWidth, kDDDataDisplayCellLabelHeight);
    [self.locationLabel sizeToFit];

}

#pragma mark - getter/setter Function

- (void)setPersonEntity:(PersonEntity *)personEntity
{
    _personEntity = personEntity;
    
    self.nameLabel.text = [NSString stringWithFormat:@"姓名:%@",self.personEntity.name];
    self.ageLabel.text = [NSString stringWithFormat:@"年龄:%@",@(self.personEntity.age)];
    NSString *genderStr = self.personEntity.gender == 0? @"女": @"男";
    self.genderLabel.text =  [NSString stringWithFormat:@"性别:%@",genderStr];
    self.locationLabel.text = [NSString stringWithFormat:@"位置:%@",self.personEntity.location];
}

@end

//  PersonEntity数据模型类
4. PersonEntity.h 类

#import <CoreData/CoreData.h>

@interface PersonEntity : NSManagedObject

@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *location;
@property (nonatomic, assign) NSInteger age;
@property (nonatomic, assign) BOOL gender;

//+ (NSString *)description;

@end

 PersonEntity.m 类的实现

#import "PersonEntity.h"

@implementation PersonEntity

@dynamic name;
@dynamic age;
@dynamic location;
@dynamic gender;

@end

// 数据设置界面的实现
5. DDDataSetVC.h
#import <UIKit/UIKit.h>
#import "PersonEntity.h"

typedef NS_ENUM(NSInteger, DDDataSetVCType) {
    DDDataSetVCTypeADD = 100,
    DDDataSetVCTypeChange
};

@interface DDDataSetVC : UIViewController

@property (nonatomic, assign) DDDataSetVCType type;
@property (nonatomic, strong) PersonEntity *personEntity;

@end
DDDataSetVC.m 文件


#import "DDDataSetVC.h"
#import "DDCoreDataManager.h"

#define kDDDataSetVCLabelTextColor                  ([UIColor blueColor])
#define kDDDataSetVCButtonTextColor                 ([UIColor blueColor])
#define kDDDataSetVCTextFieldBorderLineColor        ([UIColor magentaColor].CGColor)

#define kDDDataSetVCLabelXMargin             (50.0)
#define kDDDataSetVCLabelTopMargin           (30.0)
#define kDDDataSetVCTextFieldWidth           (200.0)
#define kDDDataSetVCTextFieldHeight          (30.0)
#define kDDDataSetVCLabelToTextFieldMargin   (8.0)

@interface DDDataSetVC ()

@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UILabel *genderLabel;
@property (nonatomic, strong) UILabel *locationLabel;
@property (nonatomic, strong) UILabel *ageLabel;

@property (nonatomic, strong) UITextField *nameTextField;
@property (nonatomic, strong) UITextField *genderTextField;
@property (nonatomic, strong) UITextField *locationTextField;
@property (nonatomic, strong) UITextField *ageTextField;

@property (nonatomic, strong) UIButton *saveButton;
@property (nonatomic, strong) UIButton *deleteButton;
@property (nonatomic, strong) UIButton *changeButton;

@end

@implementation DDDataSetVC

#pragma mark - Override Base Function

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDidTouch)];
    [self.view addGestureRecognizer:tapGesture];
    
    [self setupUI];
}

- (void)viewWillLayoutSubviews
{
    
    //姓名
    self.nameLabel.frame = CGRectMake(kDDDataSetVCLabelXMargin, kDDDataSetVCLabelTopMargin + 100.0, CGRectGetWidth(self.nameLabel.frame), CGRectGetHeight(self.nameLabel.frame));
    
    self.nameTextField.frame = CGRectMake(CGRectGetMaxX(self.nameLabel.frame) + kDDDataSetVCLabelToTextFieldMargin , CGRectGetMidY(self.nameLabel.frame) - kDDDataSetVCTextFieldHeight * 0.5, kDDDataSetVCTextFieldWidth, kDDDataSetVCTextFieldHeight);
    
    //年龄
    self.ageLabel.frame = CGRectMake(CGRectGetMinX(self.nameLabel.frame), CGRectGetMaxY(self.nameLabel.frame) + kDDDataSetVCLabelTopMargin, CGRectGetWidth(self.ageLabel.frame), CGRectGetHeight(self.ageLabel.frame));
    
    self.ageTextField.frame = CGRectMake(CGRectGetMaxX(self.ageLabel.frame) + kDDDataSetVCLabelToTextFieldMargin , CGRectGetMidY(self.ageLabel.frame) - kDDDataSetVCTextFieldHeight * 0.5, kDDDataSetVCTextFieldWidth, kDDDataSetVCTextFieldHeight);
    
    //性别
    self.genderLabel.frame = CGRectMake(CGRectGetMinX(self.nameLabel.frame), CGRectGetMaxY(self.ageLabel.frame) + kDDDataSetVCLabelTopMargin, CGRectGetWidth(self.genderLabel.frame), CGRectGetHeight(self.genderLabel.frame));
    
    self.genderTextField.frame = CGRectMake(CGRectGetMaxX(self.genderLabel.frame) + kDDDataSetVCLabelToTextFieldMargin , CGRectGetMidY(self.genderLabel.frame) - kDDDataSetVCTextFieldHeight * 0.5, kDDDataSetVCTextFieldWidth, kDDDataSetVCTextFieldHeight);
    
    //地区
    self.locationLabel.frame = CGRectMake(CGRectGetMinX(self.nameLabel.frame), CGRectGetMaxY(self.genderLabel.frame) + kDDDataSetVCLabelTopMargin, CGRectGetWidth(self.locationLabel.frame), CGRectGetHeight(self.locationLabel.frame));
    
    self.locationTextField.frame = CGRectMake(CGRectGetMaxX(self.locationLabel.frame) + kDDDataSetVCLabelToTextFieldMargin , CGRectGetMidY(self.locationLabel.frame) - kDDDataSetVCTextFieldHeight * 0.5, kDDDataSetVCTextFieldWidth, kDDDataSetVCTextFieldHeight);
    
    switch (self.type) {
        case DDDataSetVCTypeADD:
            
            self.saveButton.frame = CGRectMake(CGRectGetMinX(self.nameLabel.frame), CGRectGetMaxY(self.locationLabel.frame) + kDDDataSetVCLabelTopMargin, CGRectGetWidth(self.nameLabel.frame) + kDDDataSetVCLabelToTextFieldMargin + kDDDataSetVCTextFieldWidth, 30.0);
            break;
            
        case DDDataSetVCTypeChange:

            self.deleteButton.frame = CGRectMake(CGRectGetMinX(self.nameLabel.frame), CGRectGetMaxY(self.locationLabel.frame) + kDDDataSetVCLabelTopMargin, CGRectGetWidth(self.nameLabel.frame) + kDDDataSetVCLabelToTextFieldMargin + kDDDataSetVCTextFieldWidth, 30.0);
            
            self.changeButton.frame = CGRectMake(CGRectGetMinX(self.nameLabel.frame), CGRectGetMaxY(self.deleteButton.frame) + kDDDataSetVCLabelTopMargin, CGRectGetWidth(self.nameLabel.frame) + kDDDataSetVCLabelToTextFieldMargin + kDDDataSetVCTextFieldWidth, 30.0);
            break;
            
        default:
            break;
    }
    
}

#pragma mark - Object Private Function

- (void)setupUI
{
    //姓名
    UILabel *nameLabel = [[UILabel alloc] init];
    nameLabel.textColor = kDDDataSetVCLabelTextColor;
    nameLabel.text = @"姓名:";
    [nameLabel sizeToFit];
    [self.view addSubview:nameLabel];
    
    UITextField *nameTextField = [[UITextField alloc] init];
    nameTextField.placeholder = @"请输入名字";
    [nameTextField setBorderStyle:UITextBorderStyleLine];
    [nameTextField.layer setBorderColor:kDDDataSetVCTextFieldBorderLineColor];
    nameTextField.layer.borderWidth = 1.0;
    [self.view addSubview:nameTextField];
    
    //年龄
    UILabel *ageLabel = [[UILabel alloc] init];
    ageLabel.textColor = kDDDataSetVCLabelTextColor;
    ageLabel.text = @"年龄:";
    [ageLabel sizeToFit];
    [self.view addSubview:ageLabel];
    
    UITextField *ageTextField = [[UITextField alloc] init];
    ageTextField.placeholder = @"请输入年龄";
    [ageTextField setBorderStyle:UITextBorderStyleLine];
    [ageTextField.layer setBorderColor:kDDDataSetVCTextFieldBorderLineColor];
    ageTextField.layer.borderWidth = 1.0;
    [self.view addSubview:ageTextField];

    //性别
    UILabel *genderLabel = [[UILabel alloc] init];
    genderLabel.textColor = kDDDataSetVCLabelTextColor;
    genderLabel.text = @"性别:";
    [genderLabel sizeToFit];
    [self.view addSubview:genderLabel];
    
    UITextField *genderTextField = [[UITextField alloc] init];
    genderTextField.placeholder = @"请输入性别";
    [genderTextField setBorderStyle:UITextBorderStyleLine];
    [genderTextField.layer setBorderColor:kDDDataSetVCTextFieldBorderLineColor];
    genderTextField.layer.borderWidth = 1.0;
    [self.view addSubview:genderTextField];

    //地区
    UILabel *locationLabel = [[UILabel alloc] init];
    locationLabel.textColor = kDDDataSetVCLabelTextColor;
    locationLabel.text = @"地区:";
    [locationLabel sizeToFit];
    [self.view addSubview:locationLabel];
    
    UITextField *locationTextField = [[UITextField alloc] init];
    locationTextField.placeholder = @"请输入位置";
    [locationTextField setBorderStyle:UITextBorderStyleLine];
    [locationTextField.layer setBorderColor:kDDDataSetVCTextFieldBorderLineColor];
    locationTextField.layer.borderWidth = 1.0;
    [self.view addSubview:locationTextField];

    self.nameLabel = nameLabel;
    self.ageLabel = ageLabel;
    self.genderLabel = genderLabel;
    self.locationLabel = locationLabel;
    
    self.nameTextField = nameTextField;
    self.ageTextField = ageTextField;
    self.genderTextField = genderTextField;
    self.locationTextField = locationTextField;
    
    //保存按钮
    UIButton *saveButton = [[UIButton alloc] init];
    [saveButton setTitle:@"保存" forState:UIControlStateNormal];
    [saveButton setTitleColor:kDDDataSetVCButtonTextColor forState:UIControlStateNormal];
    [saveButton setBackgroundColor:[UIColor lightGrayColor]];
    [saveButton addTarget:self action:@selector(saveButtonDidClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:saveButton];
    
    //删除按钮
    UIButton *deleteButton = [[UIButton alloc] init];
    [deleteButton setTitle:@"删除" forState:UIControlStateNormal];
    [deleteButton setTitleColor:kDDDataSetVCButtonTextColor forState:UIControlStateNormal];
    [deleteButton setBackgroundColor:[UIColor lightGrayColor]];
    [deleteButton addTarget:self action:@selector(deleteButtonDidClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:deleteButton];
    
    //改变按钮
    UIButton *changeButton = [[UIButton alloc] init];
    [changeButton setTitle:@"修改" forState:UIControlStateNormal];
    [changeButton setTitleColor:kDDDataSetVCButtonTextColor forState:UIControlStateNormal];
    [changeButton setBackgroundColor:[UIColor lightGrayColor]];
    [changeButton addTarget:self action:@selector(changeButtonDidClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:changeButton];
    
    
    self.saveButton = saveButton;
    self.deleteButton = deleteButton;
    self.changeButton = changeButton;
    
    if (self.type == DDDataSetVCTypeChange) {
        self.nameTextField.text = self.personEntity.name;
        self.ageTextField.text = [NSString stringWithFormat:@"%ld",self.personEntity.age];
        self.genderTextField.text = [NSString stringWithFormat:@"%d",self.personEntity.gender];
        self.locationTextField.text = self.personEntity.location;
    }
    
}

- (void)showAlertView
{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"注意" message:@"内容不能为空" preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *certainAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    
    [alertVC addAction:cancelAction];
    [alertVC addAction:certainAction];
    
    [self.navigationController presentViewController:alertVC animated:YES completion:nil];
    
}


#pragma mark - Action/Event

- (void)saveButtonDidClick
{
    
    if ([self.nameTextField.text isEqualToString:@""] || [self.ageTextField.text isEqualToString:@""]|| [self.genderTextField.text isEqualToString:@""] || [self.locationTextField.text isEqualToString:@""]) {
        [self showAlertView];
        return;
    }

    self.personEntity = [NSEntityDescription insertNewObjectForEntityForName:@"PersonEntity" inManagedObjectContext:[DDCoreDataManager shareCoreDataManager].manageObjectContext];
    [self.personEntity setName:self.nameTextField.text];
    [self.personEntity setAge:[self.ageTextField.text integerValue]];
    [self.personEntity setGender:[self.genderTextField.text integerValue]];
    [self.personEntity setLocation:self.locationTextField.text];
    
    NSError *error;
    BOOL isSaveSuccess = [[DDCoreDataManager shareCoreDataManager].manageObjectContext save:&error];
    if (isSaveSuccess) {
        NSLog(@"save success");
    }
    else {
        NSLog(@"save failure, reason--%@",[error userInfo]);
    }

}

- (void)deleteButtonDidClick
{
    [[DDCoreDataManager shareCoreDataManager].manageObjectContext deleteObject:self.personEntity];
    
    NSError *error;
    BOOL isSaveSuccess = [[DDCoreDataManager shareCoreDataManager].manageObjectContext save:&error];
    if (isSaveSuccess) {
        NSLog(@"save success");
        self.nameTextField.text = @"";
        self.ageTextField.text = @"";
        self.genderTextField.text = @"";
        self.locationTextField.text = @"";
    }
    else {
        NSLog(@"save failure, reason--%@",[error userInfo]);
    }
}

- (void)changeButtonDidClick
{
    if ([self.nameTextField.text isEqualToString:@""] || [self.ageTextField.text isEqualToString:@""]|| [self.genderTextField.text isEqualToString:@""] || [self.locationTextField.text isEqualToString:@""]) {
        [self showAlertView];
        return;
    }
        
    [self.personEntity setName:self.nameTextField.text];
    [self.personEntity setAge:[self.ageTextField.text integerValue]];
    [self.personEntity setGender:[self.genderTextField.text integerValue]];
    [self.personEntity setLocation:self.locationTextField.text];
    
    NSError *error;
    BOOL isSaveSuccess = [[DDCoreDataManager shareCoreDataManager].manageObjectContext save:&error];
    if (isSaveSuccess) {
        NSLog(@"save success");
    }
    else {
        NSLog(@"save failure, reason--%@",[error userInfo]);
    }
}

- (void)tapDidTouch
{
    [self.view endEditing:YES];
}

#pragma mark - Getter/Setter Function

- (void)setType:(DDDataSetVCType)type
{
    _type = type;
    
    switch (type) {
        case DDDataSetVCTypeADD:
            self.saveButton.hidden = NO;
            self.deleteButton.hidden = YES;
            self.changeButton.hidden = YES;
            break;
            
        case DDDataSetVCTypeChange:
            self.saveButton.hidden = YES;
            self.deleteButton.hidden = NO;
            self.changeButton.hidden = NO;
            break;
        
        default:
            break;
    }
}

@end


6. CoreData的封装

这个不多说了,可以直接点我链接过去,已经封装好了。


查看结果

1、新增数据

我们新增下面这一条数据。

新增一条数据

下面我们用Navicat查询数据库,看是否有这一条数据。

新增数据查询结果

可以看见数据库里面已经有这一条数据了,再回到数据展示页面,看是否显示。

数据展示界面

可以看见数据展示界面是有这条数据的。

2、修改数据

我们修改下面这条数据,将年龄修改为900。

待修改数据
数据修改

同样我们先看数据库。

数据修改结果

可以看见数据已经修改成功,我们回到数据展示层看是否修改成功。

数据修改展示

可以看见数据修改成功。

3、 数据删除

我们先选择一条要删除的数据。

待删除数据

进行数据删除

删除数据

查看数据库

查看数据库

可以看见数据已经被删除,回到数据展示界面。

数据展示界面

可以看见数据展示界面,该条数据也被删除了。

致谢

  谢谢每一个关注我的人,谢谢大家!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,616评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,020评论 3 387
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,078评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,040评论 1 285
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,154评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,265评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,298评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,072评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,491评论 1 306
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,795评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,970评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,654评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,272评论 3 318
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,985评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,223评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,815评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,852评论 2 351

推荐阅读更多精彩内容

  • 阅读完本书,首先给我的感觉是内容有点对不起它的¥59.80定价,全书主要讲了两块内容,一块是SQLite3,...
    瑞小萌阅读 2,825评论 4 33
  • 上班之际,偷的一时清闲,以下即是自己看到这副照片的一些感触也是自己近期内心的一些看法,哈哈。我对此图的简短描述:内...
    felix_fong阅读 789评论 0 0
  • 渔歌子 《渔歌子·浪花有意千重雪》 【五代】李煜 浪花有意千重雪,桃李无言一队春。 一壶酒,一竿纶,世上如侬有几人...
    三十之前阅读 146评论 0 0
  • 最近在看荣格的书,寻找生命的意义。之所以想看这种类的书,是因为也可能是无聊了吧,感觉自己比较矛盾,不知道自...
    紫痕99阅读 243评论 0 1
  • 今天是乖巧的小雪雪。 有认真打卡!改作业好像比较敷衍。毛笔字越来越丑了,歪七扭八的。还练了一下周六野那...
    风听雪应阅读 132评论 3 1