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閱讀 227,818評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,185評論 3 414
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,656評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,647評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,446評論 6 405
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,951評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,041評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,189評論 0 287
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,718評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,602評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,800評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,316評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,045評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,419評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,671評論 1 281
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,420評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,755評論 2 371

推薦閱讀更多精彩內容

  • 閱讀完本書,首先給我的感覺是內容有點對不起它的¥59.80定價,全書主要講了兩塊內容,一塊是SQLite3,...
    瑞小萌閱讀 2,868評論 4 33
  • 上班之際,偷的一時清閑,以下即是自己看到這副照片的一些感觸也是自己近期內心的一些看法,哈哈。我對此圖的簡短描述:內...
    felix_fong閱讀 796評論 0 0
  • 漁歌子 《漁歌子·浪花有意千重雪》 【五代】李煜 浪花有意千重雪,桃李無言一隊春。 一壺酒,一竿綸,世上如儂有幾人...
    三十之前閱讀 149評論 0 0
  • 最近在看榮格的書,尋找生命的意義。之所以想看這種類的書,是因為也可能是無聊了吧,感覺自己比較矛盾,不知道自...
    紫痕99閱讀 252評論 0 1
  • 今天是乖巧的小雪雪。 有認真打卡!改作業好像比較敷衍。毛筆字越來越丑了,歪七扭八的。還練了一下周六野那...
    風聽雪應閱讀 134評論 3 1