iOS coreData

时间:2022-10-23 17:47:10

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];

}