static int row=0;

static const NSString *kStoryboardName = @"LRCoreDataViewController";

static const NSString *kIdentifier = @"LRCoreDataViewController";



@interface LRCoreDataViewControllerCellInfo : NSObject

@property (nonatomic,strong) NSString *name;

@property (nonatomic,strong) NSString *city;

@property (nonatomic,strong) NSString *state;

@end

@implementation LRCoreDataViewControllerCellInfo

@end

typedef LRCoreDataViewControllerCellInfo CellInfo_t;



@interface LRCoreDataViewController ()<LRAlertViewManagerDelegate,UITableViewDataSource,UITableViewDelegate>

{

    NSManagedObjectContext *_context;

}

@property (strong, nonatomic) IBOutlet UITableView *myTableView;

@property (nonatomic,strong) NSMutableArray *cellInfoArray;

@end



@implementation LRCoreDataViewController

@synthesize failedBankInfos;

@synthesize managedObjectContext;

+(instancetype)createViewController:(id)createArgs{

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:(NSString *)kStoryboardName bundle:nil];

    LRCoreDataViewController *vc = [storyboard instantiateViewControllerWithIdentifier:(NSString *)kIdentifier];

    return vc;

}

- (void)viewDidLoad {

    [super viewDidLoad];

    self.view.backgroundColor=[UIColor cyanColor];

    [self initCoreData];

    [self initRightItem];

    [self initTableView];

    [self setExtraCellLineHidden:self.myTableView];

    //[self openDataBase];

    self.myDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

}

- (void)openDataBase{

    NSManagedObjectModel *model=[NSManagedObjectModel mergedModelFromBundles:nil];

    NSPersistentStoreCoordinator *coodinator=[[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:model];

    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/mydatabase.db"];

    NSError *error=nil;

    [coodinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:path] options:nil error:&error];

    if (error) {

        NSLog(@"打开数据库失败");

    }else{

        NSLog(@"创建数据库成功");

        _context=[[NSManagedObjectContext alloc]init];

        _context.persistentStoreCoordinator=coodinator;

    }

}

- (void)setExtraCellLineHidden: (UITableView *)tableView{

    UIView *view =[ [UIView alloc]init];

    view.backgroundColor = [UIColor clearColor];

    [tableView setTableFooterView:view];

    [tableView setTableHeaderView:view];

}

- (void)initTableView{

    self.myTableView.delegate=self;

    self.myTableView.dataSource=self;

}

- (void)initRightItem{

    UIButton *rightBtn = [[UIButton alloc]init];

    [rightBtn setFrame:CGRectMake(0, 0, 39, 36)];

    [rightBtn setImage:[UIImage imageNamed:@"addData"] forState:UIControlStateNormal];

    rightBtn.showsTouchWhenHighlighted = YES;

    [rightBtn addTarget:self action:@selector(addData) forControlEvents:UIControlEventTouchUpInside];

    UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];

    self.navigationItem.rightBarButtonItem = buttonItem;

}

#pragma mark - 向数据库中添加数据,并显示在当前界面

- (void)addData{

    LRAlertViewManager *manager=[LRAlertViewManager sharedAlertViewManager];

    manager.delegate=self;

    [manager showAlertView];

}

- (void)clickButton:(int)tag{

    if (tag==99) {

        NSError *error;

        //创建一个指向数据库的指针。管理对象,上下文。持久性存储模型对象

        NSManagedObjectContext *context=[self managedObjectContext];

        NSManagedObject *BankInfo=[NSEntityDescription insertNewObjectForEntityForName:@"BankInfo" inManagedObjectContext:context];

        [BankInfo    setValue:@"姓名" forKey:@"name"];

        [BankInfo    setValue:@"城市" forKey:@"city"];

        [BankInfo    setValue:@"状态" forKey:@"sta"];

        [BankInfo    setValue:[NSNumber numberWithInt:row] forKey:@"row"];

        NSManagedObject    *bankDetails=[NSEntityDescription insertNewObjectForEntityForName:@"BankDetails" inManagedObjectContext:context];

        [bankDetails setValue:[NSDate date] forKey:@"hh"];

        [bankDetails setValue:[NSDate date] forKey:@"mm"];

        [bankDetails setValue:[NSNumber numberWithInt:12345] forKey:@"zip"];

        [bankDetails setValue:BankInfo forKey:@"info"];

        [bankDetails    setValue:bankDetails forKey:@"details"];

        if (![context save:&error]) {

            NSLog(@"Whoops, could not save:%@",[error localizedDescription]);

        }

        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

        NSEntityDescription *entity = [NSEntityDescription entityForName:@"FailedBankInfo" inManagedObjectContext:context];

        [fetchRequest setEntity:entity];

        NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];

        for (FailedBankInfo *info in fetchedObjects) {

            NSLog(@"row: %d", info.row);

            FailedBankDetails *details = info.details;

            NSLog(@"Zip: %@", details.zip);

        }

        NSFetchRequest *fetchRequest2 = [[NSFetchRequest alloc] init];

        NSEntityDescription *entity2 = [NSEntityDescription entityForName:@"FailedBankInfo" inManagedObjectContext:managedObjectContext];

        [fetchRequest2 setEntity:entity2];

        NSError *error2;

        self.failedBankInfos = [managedObjectContext executeFetchRequest:fetchRequest2 error:&error2];

        [self.myTableView reloadData];

        row++;

    }else if (tag==100){

        NSManagedObjectContext *context = [self managedObjectContext];

        NSEntityDescription *description = [NSEntityDescription entityForName:@"FailedBankInfo" inManagedObjectContext:context];

        NSFetchRequest *request = [[NSFetchRequest alloc] init];

        [request setIncludesPropertyValues:NO];

        [request setEntity:description];

        NSError *error = nil;

        NSArray *datas = [context executeFetchRequest:request error:&error];

        if (!error && datas && [datas count]){

            for (NSManagedObject *obj in datas){

                [context deleteObject:obj];

            }

            if (![context save:&error]){

                NSLog(@"error:%@",error);

            }

        }

        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

        NSEntityDescription *entity = [NSEntityDescription entityForName:@"FailedBankInfo" inManagedObjectContext:managedObjectContext];

        [fetchRequest setEntity:entity];

        NSError *error2;

        self.failedBankInfos = [managedObjectContext executeFetchRequest:fetchRequest error:&error2];

        [self.myTableView reloadData];

    }

}

#pragma mark -初始化 NSArray存数据

- (void)initCoreData{

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"FailedBankInfo" inManagedObjectContext:managedObjectContext];

    [fetchRequest setEntity:entity];

    NSError *error;

    self.failedBankInfos = [managedObjectContext executeFetchRequest:fetchRequest error:&error];

    self.title = @"CoreData";

}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return failedBankInfos.count;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    

    if (!cell) {

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];

    }

    FailedBankInfo *info = [failedBankInfos objectAtIndex:indexPath.row];

    cell.textLabel.text = info.name;

    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@, %@",info.city, info.state];

    UILabel *deleteLabel=[[UILabel alloc]initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width-200, 5, 200, 40)];

    deleteLabel.text=@"向左滑动删除CoreData数据";

    [cell.contentView addSubview:deleteLabel];

    return cell;

}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{

    return UITableViewCellEditingStyleDelete;

}

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{

    return @"删除";

}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{

    NSManagedObjectContext *context = [self managedObjectContext];

    NSEntityDescription *description = [NSEntityDescription entityForName:@"FailedBankInfo" inManagedObjectContext:context];

    NSFetchRequest *request = [[NSFetchRequest alloc] init];

    [request setIncludesPropertyValues:NO];

    [request setEntity:description];

    NSError *error = nil;

    NSArray *datas = [context executeFetchRequest:request error:&error];

    if (!error && datas && [datas count]){

        [context deleteObject:datas[indexPath.row]];

        if (![context save:&error]){

            NSLog(@"error:%@",error);

        }

    }

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"FailedBankInfo" inManagedObjectContext:managedObjectContext];

    [fetchRequest setEntity:entity];

    NSError *error2;

    self.failedBankInfos = [managedObjectContext executeFetchRequest:fetchRequest error:&error2];

    [self.myTableView deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];

    [self.myTableView reloadData];

}

iOS coreData的更多相关文章

  1. iOS CoreData技术学习资源汇总

    一.CoreData学习指引 1. 苹果官方:Core Data Programming Guide 什么是CoreData? 创建托管对象模型 初始化Core Data堆栈 提取对象 创建和修改自定 ...

  2. IOS CoreData 多表查询demo解析

    在IOS CoreData中,多表查询上相对来说,没有SQL直观,但CoreData的功能还是可以完成相关操作的. 下面使用CoreData进行关系数据库的表与表之间的关系演示.生成CoreData和 ...

  3. iOS CoreData (一) 增删改查

    代码地址如下:http://www.demodashi.com/demo/11041.html Core Data是iOS5之后才出现的一个框架,本质上是对SQLite的一个封装,它提供了对象-关系映 ...

  4. iOS CoreData (二) 版本升级和数据库迁移

    前言:最近ChinaDaily项目需要迭代一个新版本,在这个版本中CoreData数据库模型上有新增表.实体字段的增加,那么在用户覆盖安装程序时就必须要进行CoreData数据库的版本升级和旧数据迁移 ...

  5. IOS CoreData 多表查询(下)

    http://blog.csdn.net/fengsh998/article/details/8123392 在iOS CoreData中,多表查询上相对来说,没有SQL直观,但COREDATA的功能 ...

  6. iOS CoreData 介绍和使用(以及一些注意事项)

    iOS CoreData介绍和使用(以及一些注意事项) 最近花了一点时间整理了一下CoreData,对于经常使用SQLite的我来说,用这个真的有点用不惯,个人觉得实在是没发现什么亮点,不喜勿喷啊.不 ...

  7. iOS CoreData介绍和使用(以及一些注意事项)

    iOS CoreData介绍和使用(以及一些注意事项) 最近花了一点时间整理了一下CoreData,对于经常使用SQLite的我来说,用这个真的有点用不惯,个人觉得实在是没发现什么亮点,不喜勿喷啊.不 ...

  8. iOS - CoreData 数据库存储

    1.CoreData 数据库 CoreData 是 iOS SDK 里的一个很强大的框架,允许程序员以面向对象的方式储存和管理数据.使用 CoreData 框架,程序员可以很轻松有效地通过面向对象的接 ...

  9. iOS coreData问题

    iOS常见错误-CoreData: Cannot load NSManagedObjectModel.nil is an illegal URL parameter
这是因为在工程中CoreData的 ...

  10. ios Coredata 的 rollback undo 等事物处理函数

    首先说明 ios 中 NSManagedObjectContext 默认的 undoManager是nil的,就是说 undo 和 redo 都是没用的. 但是 rollback函数和reset函数是 ...

随机推荐

  1. 游戏开发实验室的内部讲座总结----c++

     第三节  动态内存分配new和delete 经过调试设置断点,发现new 函数事实上还是调用的malloc函数. 第四节  引用 一个变量是能够有多个引用的,引用也是能够传递的.  常量是不能有 ...

  2. ReactNavtive框架教程(2)

    , alignItems: 'center' } }); 标准的 CSS 属性.尽管用CSS比在IB设置UI样式的可视化要差.但总比在viewDidLoad()方法中用代码写要好一些. 然后增加下面代 ...

  3. PHP获取当前页面完整的URL

    #测试网址: http://localhost/blog/testurl.php?id=5 //获取域名或主机地址 echo $_SERVER['HTTP_HOST']."<br> ...

  4. QTP小应用一则

    昨天收到一个任务,将270多个视频文件按照统一的编码要求,转换为其他格式,而且给的转换器居然不能批量转换! 在痛苦地转换了30多个之后,我才想起来使用QTP的数据驱动测试方法可以解决这个问题! 于是我 ...

  5. u-boot: Error: Can&#39;t overwrite &quot;ethaddr&quot;

    When try to execute following command, It reports error as following: --->8--- U-Boot> setenv ...

  6. 辛星解读为什么PHP须要模板

    近期有个人问我:为什么PHP须要模板呢?整个站点的编写都是我一个人完毕的,从前端到后端,都是这样,我一个人写站点是不是就不须要模板了呢?我当时还真给问住了,也没想好非常合适的回答它的方式,于是就随便说 ...

  7. 用python输出汉字字库

    问题1:如果我们知道汉字编码范围是0x4E00到0x9FA5,怎么从十六进制的编码转成人类可读的字呢? 问题2:怎么把unicode编码的字写入文件呢,假设直接用open()的话,会提示Unicode ...

  8. 利用Sambaserver在Ubuntu系统和Win7系统间共享目录

    1 介绍 如今是网络化的时代,我们每一个人要更好的发展.离不开网络化.信息化的支持.利用网络的支持.在不同的操作系统间共享文件等信息,是计算机专业学生必备的一项技能. 本文所讲的就是怎样建立.设置.链 ...

  9. php我们需要把握面试题目金鸡基础

    1.session与cookie差分? 答:session:储存用户訪问的全局唯一变量,存储在server上的php指定的文件夹中的(session_dir)的位置进行的存放 cookie:用来存储连 ...

  10. 数据验证validator 与 DWZ

    在进行系统经常使用的数据验证.数据验证可以编写自己的,它也可以用来作为现在.现在,记录这两个库的使用, validator <!DOCTYPE HTML PUBLIC "-//W3C/ ...