FMDB增加修改删除功能的实现

来源:互联网 发布:linux async同步文件 编辑:程序博客网 时间:2024/05/16 13:38
////  AppDelegate.h//  fmdb////  Created by APPLE on 16/10/25.//  Copyright © 2016年 Apple. All rights reserved.//#import <UIKit/UIKit.h>#import <CoreData/CoreData.h>@interface AppDelegate : UIResponder <UIApplicationDelegate>@property (strong, nonatomic) UIWindow *window;@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;- (void)saveContext;- (NSURL *)applicationDocumentsDirectory;@end
//  AppDelegate.m//  fmdb////  Created by APPLE on 16/10/25.//  Copyright © 2016年 Apple. All rights reserved.//#import "AppDelegate.h"#import "TableViewController.h"@interface AppDelegate ()@end@implementation AppDelegate- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    // Override point for customization after application launch.        //添加导航条    TableViewController *table =[[TableViewController alloc]init];        UINavigationController *nav =[[UINavigationController alloc]initWithRootViewController:table];        self.window.rootViewController = nav;        self.window.backgroundColor = [UIColor whiteColor];        return YES;}- (void)applicationWillResignActive:(UIApplication *)application {    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.}- (void)applicationDidEnterBackground:(UIApplication *)application {    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.}- (void)applicationWillEnterForeground:(UIApplication *)application {    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.}- (void)applicationDidBecomeActive:(UIApplication *)application {    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.}- (void)applicationWillTerminate:(UIApplication *)application {    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.    // Saves changes in the application's managed object context before the application terminates.    [self saveContext];}#pragma mark - Core Data stack@synthesize managedObjectContext = _managedObjectContext;@synthesize managedObjectModel = _managedObjectModel;@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;- (NSURL *)applicationDocumentsDirectory {    // The directory the application uses to store the Core Data store file. This code uses a directory named "Apple.fmdb" in the application's documents directory.    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];}- (NSManagedObjectModel *)managedObjectModel {    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.    if (_managedObjectModel != nil) {        return _managedObjectModel;    }    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"fmdb" withExtension:@"momd"];    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];    return _managedObjectModel;}- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.    if (_persistentStoreCoordinator != nil) {        return _persistentStoreCoordinator;    }        // Create the coordinator and store        _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"fmdb.sqlite"];    NSError *error = nil;    NSString *failureReason = @"There was an error creating or loading the application's saved data.";    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {        // Report any error we got.        NSMutableDictionary *dict = [NSMutableDictionary dictionary];        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";        dict[NSLocalizedFailureReasonErrorKey] = failureReason;        dict[NSUnderlyingErrorKey] = error;        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];        // Replace this with code to handle the error appropriately.        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);        abort();    }        return _persistentStoreCoordinator;}- (NSManagedObjectContext *)managedObjectContext {    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)    if (_managedObjectContext != nil) {        return _managedObjectContext;    }        NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];    if (!coordinator) {        return nil;    }    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];    [_managedObjectContext setPersistentStoreCoordinator:coordinator];    return _managedObjectContext;}#pragma mark - Core Data Saving support- (void)saveContext {    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;    if (managedObjectContext != nil) {        NSError *error = nil;        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {            // Replace this implementation with code to handle the error appropriately.            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);            abort();        }    }}@end

///  ViewController.h//  fmdb////  Created by APPLE on 16/10/25.//  Copyright © 2016年 Apple. All rights reserved.//#import <UIKit/UIKit.h>#import "Model.h"@interface ViewController : UIViewController@property(nonatomic,strong) Model *mm;@property (nonatomic,assign) NSInteger kk;@end

///  ViewController.m//  fmdb////  Created by APPLE on 16/10/25.//  Copyright © 2016年 Apple. All rights reserved.//#import "ViewController.h"#import "Data.h"@interface ViewController (){    //输入框和按钮    UITextField *f1,*f2;    UIButton *bun;}@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.        //输入框    f1 = [[UITextField alloc]initWithFrame:CGRectMake(84, 84, 200, 35)];    f1.layer.borderWidth = 1;    [self.view addSubview:f1];        f2 = [[UITextField alloc]initWithFrame:CGRectMake(84, 154, 200, 35)];    f2.layer.borderWidth = 1;    //把按钮加到视图    [self.view addSubview:f2];    //保存按钮    //创建按钮    bun =[UIButton buttonWithType:UIButtonTypeCustom];    //位置    bun.frame = CGRectMake(self.view.center.x - 40, 440, 180, 40);    //按钮名称    [bun setTitle:@"保存" forState:UIControlStateNormal];    //按钮颜色    [bun setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];    //按钮方法    [bun addTarget:self action:@selector(bunn) forControlEvents:UIControlEventTouchUpInside];    [self.view addSubview:bun];        //背景颜色    self.view.backgroundColor =[UIColor whiteColor];        if(self.kk == 11)    {        //导航栏名字        self.navigationItem.title = @"添加";    }    else    {        self.navigationItem.title = @"修改";                //把输入框的取出来        f1.text = self.mm.name;        f2.text = self.mm.age;    }        }//按钮的响应方法-(void)bunn{    //kk =1 的话是添加 哪个是修改    if(self.kk == 11)    {        Model*mm =[[Model alloc]init];        mm.name = f1.text;        mm.age = f2.text;                //调用添加方法        [[Data shardData]insertData:mm];    }    else    {        Model *mm = [[Model alloc]init];        mm.name = f1.text;        mm.age = f2.text;        //调用修改方法        [[Data shardData]updataData:mm];            }    }- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end

////  TableViewController.h// / fmdb////  Created by APPLE on 16/10/25.//  Copyright © 2016年 Apple. All rights reserved.//#import <UIKit/UIKit.h>@interface TableViewController : UITableViewController@end

//  TableViewController.m//   fmdb////  Created by APPLE on 16/10/25.//  Copyright © 2016年 Apple. All rights reserved.//#import "TableViewController.h"#import "Model.h"#import "Data.h"#import "ViewController.h"@interface TableViewController (){    NSMutableArray *dataSource;}@end@implementation TableViewController//页面将要显示时加载数据-(void)viewWillAppear:(BOOL)animated{    [super viewWillAppear:animated];    dataSource = [[Data shardData]selectData];    [self.tableView reloadData];}- (void)viewDidLoad {    [super viewDidLoad];        //导航条按钮    self.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc]initWithTitle:@"添加" style:UIBarButtonItemStylePlain target:self action:@selector(cc)];}//按钮的响应方法-(void)cc{    //跳转页面    ViewController *vv= [[ViewController alloc]init];    vv.kk =11;    [self.navigationController pushViewController:vv animated:YES];}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}#pragma mark - Table view data source//分区- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {    return 1;}//多少单元格- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {    return dataSource.count;}//给表格赋值- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {        static NSString *str = @"MyCell";        UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:str];    if(cell == nil)    {        cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:str];    }    Model *mm = dataSource[indexPath.row];        cell.textLabel.text = [NSString stringWithFormat:@"姓名:%@",mm.name];    cell.detailTextLabel.text = [NSString stringWithFormat:@"年龄:%@",mm.age];        return cell;}//侧滑删除-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{    [[Data shardData]deleteData:[dataSource [indexPath.row]stu_id]];        dataSource =[[Data shardData]selectData];    [self.tableView reloadData];}//修改-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{    ViewController *v = [[ViewController alloc]init];        [self.navigationController pushViewController:v animated:YES];}/*// Override to support conditional editing of the table view.- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {    // Return NO if you do not want the specified item to be editable.    return YES;}*//*// Override to support editing the table view.- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {    if (editingStyle == UITableViewCellEditingStyleDelete) {        // Delete the row from the data source        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];    } else if (editingStyle == UITableViewCellEditingStyleInsert) {        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view    }   }*//*// Override to support rearranging the table view.- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {}*//*// Override to support conditional rearranging of the table view.- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {    // Return NO if you do not want the item to be re-orderable.    return YES;}*//*#pragma mark - Navigation// In a storyboard-based application, you will often want to do a little preparation before navigation- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {    // Get the new view controller using [segue destinationViewController].    // Pass the selected object to the new view controller.}*/@end

////  Data.h//  fmdb////  Created by APPLE on 16/10/25.//  Copyright © 2016年 Apple. All rights reserved.//#import <Foundation/Foundation.h>#import "FMDB.h"#import "Model.h"#import "Data.h"@interface Data : NSObject+(instancetype)shardData;-(void)initData;-(BOOL)insertData:(Model *)mmoo;-(BOOL)deleteData:(NSInteger)iidd;-(BOOL)updataData:(Model*)mmoo;-(NSMutableArray *)selectData;@end

////  Data.m//  fmdb////  Created by APPLE on 16/10/25.//  Copyright © 2016年 Apple. All rights reserved.//#import "Data.h"static FMDatabase * dataBase;static Data *data;@implementation Data+(instancetype)shardData{        static dispatch_once_t onceToken;        dispatch_once(&onceToken,^{                data = [[Data alloc]init];                [data initData];   });        return data;      }+(instancetype)allocWithZone:(struct _NSZone*)zone{        if (data == nil){                data = [super allocWithZone:zone];            }   return data;      }-(void)initData{        //获取数据库的路径        NSString *strpath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];        //拼接路径        NSString *path = [strpath stringByAppendingString:@"FMDB.TABLE"];        //初始化数据表        dataBase = [[FMDatabase alloc]initWithPath:path];        //打开数据库        if ([dataBase open]) {                NSLog(@"打开成功");                [dataBase executeUpdate:@"create table Mondel(stu_id integer primary key autoincrement,name text,age text)"];    }    else   {        NSLog(@"打开失败");    }    }-(BOOL)insertData:(Model *)mmoo{        //打开数据库        [dataBase open];        //创建插入语句        BOOL result = [dataBase executeUpdate:@"insert into Mondel(name,age)values(?,?)",mmoo.name,mmoo.age];        if (result) {        NSLog(@"添加成功");    }    else    {        NSLog(@"添加失败");    }        //关闭数据库        [dataBase close];        return result;}-(BOOL)deleteData:(NSInteger)iidd{        //打开数据库        [dataBase open];        //创建删除语句        BOOL result =[dataBase executeUpdateWithFormat:@"delete from Mondel where stu_id = %ld",iidd];        if (result) {        NSLog(@"删除成功");    }        else    {        NSLog(@"删除失败");            }        //关闭数据库        [dataBase close];        return result;}-(BOOL)updataData:(Model*)mmoo{        //打开数据库        [dataBase open];        //创建修改语句        BOOL result = [dataBase executeUpdateWithFormat:@"update Mondel set name = %@,age = %@ where stu_id = %ld",mmoo.name,mmoo.age,mmoo.stu_id];        if (result) {        NSLog(@"修改成功");    }    else    {        NSLog(@"修改失败");    }        //关闭数据库        [dataBase close];        return result;}-(NSMutableArray *)selectData{        //打开数据库        [dataBase open];        //创建查找语句        FMResultSet *resultset = [dataBase executeQuery:@"select *from Mondel"];        NSMutableArray *Marr = [NSMutableArray array];        while ([resultset next]) {                Model *mon = [[Model alloc]init];                mon.stu_id = [resultset intForColumn:@"stu_id"];                mon.name = [resultset stringForColumn:@"name"];                mon.age = [resultset stringForColumn:@"age"];                [Marr addObject:mon];            }        return Marr;}@end

////  Model.h//  fmdb////  Created by APPLE on 16/10/25.//  Copyright © 2016年 Apple. All rights reserved.//#import <Foundation/Foundation.h>@interface Model : NSObject@property (nonatomic,strong)NSString *name;@property (nonatomic,strong)NSString *age;@property (nonatomic,assign) NSInteger stu_id;@end

////  Model.m//  fmdb////  Created by APPLE on 16/10/25.//  Copyright © 2016年 Apple. All rights reserved.//#import "Model.h"@implementation Model@end


1 0