Xcode8后CoreData的使用

E9322D5A-7317-4297-B55F-007B4D452E61.png

一、創(chuàng)建xxx.xcdatamodeld的可視化模型文件 eg:MyCoreData.xcdatamodeld
并且添加兩個(gè)屬性 name age

直接上代碼:

import "ViewController.h"

import "AppDelegate.h"

import "FirstCoreData+CoreDataClass.h"

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>
/****** table ******/
@property (strong, nonatomic) UITableView *myTable;
/****** dataSourse ******/
@property (strong, nonatomic) NSMutableArray *dataSourse;

/****** appdelegate ******/
@property (strong, nonatomic) AppDelegate *myAppdelegate;
@end

@implementation ViewController

pragma mark - lazy

  • (UITableView *)myTable{
    if (!_myTable) {
    _myTable = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _myTable.delegate = self;
    _myTable.dataSource = self;
    _myTable.rowHeight = 50;
    }
    return _myTable;
    }
  • (NSMutableArray *)dataSourse{
    if (!_dataSourse) {
    _dataSourse = [NSMutableArray array];
    }
    return _dataSourse;
    }

pragma mark - 系統(tǒng)

  • (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //查詢數(shù)據(jù)
    //創(chuàng)建NSFetchRequest對(duì)象
    NSFetchRequest *fetchRequest= [[NSFetchRequest alloc]initWithEntityName:@"FirstCoreData"];
    //排序
    NSSortDescriptor *sort = [[NSSortDescriptor alloc]initWithKey:@"age" ascending:YES];
    fetchRequest.sortDescriptors = @[sort]; //這可以添加多種排序
    NSError *error = nil;
    NSArray *tempArray = [self.myAppdelegate.persistentContainer.viewContext executeFetchRequest:fetchRequest error:&error];

    if (error) {
    NSLog(@"查詢失敗:%@",error);
    }else{

      [self.dataSourse addObjectsFromArray:tempArray];  //添加到數(shù)據(jù)
    

    }

}

  • (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"coreDataTest";
    UIBarButtonItem *right = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addData)];
    self.navigationItem.rightBarButtonItem = right;

    UIBarButtonItem *left = [[UIBarButtonItem alloc]initWithTitle:@"長(zhǎng)按修改" style:UIBarButtonItemStylePlain target:self action:@selector(change)];
    self.navigationItem.leftBarButtonItem = left;

    [self.view addSubview:self.myTable];
    self.myAppdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

}

pragma mark - addData

  • (void)change{

}

  • (void)addData{
    //添加數(shù)據(jù)
    NSEntityDescription *description = [NSEntityDescription entityForName:@"FirstCoreData" inManagedObjectContext:self.myAppdelegate.persistentContainer.viewContext];
    FirstCoreData *first = [[FirstCoreData alloc]initWithEntity:description insertIntoManagedObjectContext:self.myAppdelegate.persistentContainer.viewContext];
    first.name = @"ZhangSan";
    int age = arc4random() % 30 + 1;
    first.age = [NSString stringWithFormat:@"%d",age];
    [self.dataSourse addObject:first]; //添加數(shù)據(jù)源
    [self.myTable insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.dataSourse.count - 1 inSection:0]] withRowAnimation:UITableViewRowAnimationLeft]; //table插入數(shù)據(jù)
    [self.myAppdelegate saveContext]; //保存數(shù)據(jù)

}

pragma mark - table delegate datasourse

  • (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
    }

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

  • (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *cellID = [NSString stringWithFormat:@"%ld%ld",(long)indexPath.section,(long)indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    //獲取數(shù)據(jù)
    FirstCoreData *first = self.dataSourse[indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"name:%@ age:%@",first.name, first.age];
    // 添加長(zhǎng)按手勢(shì)操作
    UILongPressGestureRecognizer * longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(cellLongPress:)];
    [cell addGestureRecognizer:longPressGesture];

    return cell;
    }
    //刪除

  • (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
    //1.獲取數(shù)據(jù)源
    FirstCoreData *first = self.dataSourse[indexPath.row];
    //2.刪除數(shù)據(jù)數(shù)據(jù)源
    [self.dataSourse removeObject:first];
    //3.刪除單元格
    [self.myTable deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    //4.刪除數(shù)據(jù)管理器中的數(shù)據(jù)
    [self.myAppdelegate.persistentContainer.viewContext deleteObject:first];
    //5.保存
    [self.myAppdelegate saveContext];

    }
    }

  • (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"刪除";
    }
    // 長(zhǎng)按修改

  • (void)cellLongPress:(UILongPressGestureRecognizer *)tap{

    CGPoint index = [tap locationInView:self.myTable];
    NSIndexPath *indexPath = [self.myTable indexPathForRowAtPoint:index]; //獲取行數(shù)
    UITableViewCell *cell = (UITableViewCell *)tap.view; //強(qiáng)轉(zhuǎn)cell

    FirstCoreData *first = self.dataSourse[indexPath.row];
    first.name = @"修改后的閃閃發(fā)光";
    cell.textLabel.textColor = [UIColor orangeColor];
    [self.myTable reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];

    //保存數(shù)據(jù)
    [self.myAppdelegate saveContext];

}

x下載地址:http://code.cocoachina.com/view/135025

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容