苹果给我们自带了sqlite ,但是用起来非常不友好,所以呢,一些大神在他原来的基础上封装了一层 FMDB libsqlite3.tbd
今天,我们就来做一个简单的基于 FMDB 的数据库基本操作
首先,我们应该去下载FMDB工程项目https://github.com/ccgus/fmdb.git
下载下来的是一个demo,大家可以把src文件夹拖出来再改名为FMDB,拖进自己的项目中就行了
在项目里添加libsqlite3.dylib(xcode7的朋友添加 libsqlite3.tbd ),还有头文件#import "FMDatabase.h"(#import "FMDatabaseQueue.h")这个我们现在还是用不到,先不去管它了,我们先来看看他的效果
看到了,我们要做的有三个界面,第一个是就是简单的通讯录了,第二个是添加界面,第三了就是 search了
里面有一个我自己封装的XFNotices 这个其实很简单,我先贴上源码 或者你们直接在 demo 中抠出来
线上 Code4App demo 地址: FMDB 基本使用
先说一下,我这是用 frame 布局,没有任何 SB XIB 直接贴到工程中即可使用
我们先把主体框架搭建好
首先,我们应该先写一个单例,原因我就不一一概述了
创建继承与 NSObject 的文件
#import "YXFDataFromDataBase.h"
#import <Foundation/Foundation.h> @interface YXFDataFromDataBase : NSObject @property(retain,nonatomic) NSString *nameFromClass; @property(retain,nonatomic)NSString *ageFromClass; @property(retain,nonatomic)NSString *IDFromClass; @property(retain,nonatomic)NSMutableArray *nameArrayFromClass; +(YXFDataFromDataBase *)shareFromDataBase; @end
#import "YXFDataFromDataBase.m"
#import "YXFDataFromDataBase.h" @implementation YXFDataFromDataBase + (YXFDataFromDataBase *)shareFromDataBase { static YXFDataFromDataBase *sharedInstance = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ if (sharedInstance == nil) { sharedInstance = [[YXFDataFromDataBase alloc] init]; } }); return sharedInstance; } - (instancetype)init { self = [super init]; if (self) { _nameFromClass = @""; _ageFromClass = @""; _IDFromClass = @""; _nameArrayFromClass = [[NSMutableArray alloc]initWithCapacity:0]; } return self; } @end
好了,单例写好了,以后我们用起来超级方便了哦!!!
接着,在 AppDelegate.m 的头文件中 引入:
#import "YXFAddressViewController.h"
#import "YXFAddUserViewController.h"
#import "YXFSearchViewController.h"
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; self.window.backgroundColor = [UIColor whiteColor]; [self.window makeKeyAndVisible]; UITabBarController *tabbar = [[UITabBarController alloc] init]; YXFAddressViewController *addressVC = [[YXFAddressViewController alloc] init]; UINavigationController *addressNC = [[UINavigationController alloc] initWithRootViewController:addressVC]; addressNC.tabBarItem = [[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemContacts tag:101]; YXFAddUserViewController *addUserVC = [[YXFAddUserViewController alloc] init]; UINavigationController *addUserNC = [[UINavigationController alloc] initWithRootViewController:addUserVC]; addUserNC.tabBarItem = [[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemFavorites tag:102]; YXFSearchViewController *searchVC = [[YXFSearchViewController alloc] init]; UINavigationController *searchNC = [[UINavigationController alloc] initWithRootViewController:searchVC]; searchNC.tabBarItem = [[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemSearch tag:103]; tabbar.viewControllers = @[addressNC,addUserNC,searchNC]; self.window.rootViewController = tabbar; return YES; }
接下来就是创建第一个通讯录 VC
创建一个 UITableViewController 就可以了 还有有一个自定义的 UITableViewCell
#import "YXFAddressViewController.h"
#import <UIKit/UIKit.h> @interface YXFAddressViewController : UITableViewController @property (nonatomic, strong) NSString *paths; @property (nonatomic, strong) NSMutableArray *nameArray; @property (nonatomic, strong) NSMutableArray *ageArray; @property (nonatomic, strong) NSMutableArray *IDArray; @end
#import "YXFAddressViewController.m"
#import "YXFAddressViewController.h" //这个是自己写的一个提示框 #import "XFNotices.h" #import "FMDatabase.h" #import "FMDatabaseQueue.h" #import "YXFAddressViewCell.h" #import "YXFDataFromDataBase.h" #import "YXFAddUserViewController.h" @interface YXFAddressViewController () @end @implementation YXFAddressViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; [self.tableView registerClass:[YXFAddressViewCell class] forCellReuseIdentifier:@"cell"]; self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(modifyDatabase)]; } - (void)viewWillAppear:(BOOL)animated { NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]; NSString *path = [document stringByAppendingPathComponent:@"USER.sqlite"]; self.paths = path; //注意以上三句话是获取数据库路径必不可少的,在viewDidload之前就已经准备好了 self.nameArray = [[NSMutableArray alloc]init]; self.ageArray = [[NSMutableArray alloc]init]; self.IDArray = [[NSMutableArray alloc]init]; [self createTable]; [self getAllDatabase]; } #pragma mark - Table view data source - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.nameArray.count + 1; } - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath { if (indexPath.row == 0) { return nil; }else { return indexPath; } } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { YXFAddressViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath]; if (indexPath.row == 0) { cell.nameLabel.text = @"姓名"; cell.ageLabel.text = @"年龄"; cell.ID.text = @"ID"; }else { cell.nameLabel.text = [self.nameArray objectAtIndex:indexPath.row -1]; cell.ageLabel.text = [self.ageArray objectAtIndex:indexPath.row - 1]; cell.ID.text = [self.IDArray objectAtIndex:indexPath.row - 1]; } return cell; } - (void)createTable { NSFileManager *fileManager = [NSFileManager defaultManager]; if (![fileManager fileExistsAtPath:self.paths]) { NSLog(@"表不存在,创建表"); FMDatabase *db =[FMDatabase databaseWithPath:self.paths]; if ([db open]) { NSString *sql = @"CREATE TABLE 'USER'('id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 'name' VARCHAR(20),'age' VARCHAR(20),'idcode' VARCHAR(30)) ";//sql语句 BOOL success = [db executeUpdate:sql]; if (!success) { NSLog(@"error when create table "); }else{ NSLog(@"create table succeed"); } [db close]; }else{ NSLog(@"database open error"); } } } - (void)getAllDatabase//从数据库中获得所有数据 { FMDatabase *db = [FMDatabase databaseWithPath:self.paths]; if ([db open]) { NSString *sql = @"SELECT * FROM USER"; FMResultSet *rs = [db executeQuery:sql]; while ([rs next]) { NSString *name = [rs stringForColumn:@"name"]; NSString *age = [rs stringForColumn:@"age"]; NSString *ID = [rs stringForColumn:@"idcode"]; [self.nameArray addObject:name]; [self.ageArray addObject:age]; [self.IDArray addObject:ID]; } [[YXFDataFromDataBase shareFromDataBase].nameArrayFromClass arrayByAddingObjectsFromArray:self.nameArray]; NSLog(@"self.nameArray==%@",self.nameArray); [db close]; [self.tableView reloadData]; } } //选中相应的行,进入更新界面,注意这里没有对数据库进行操作 - (void)modifyDatabase { NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow]; if (indexPath == nil) { [XFNotices noticesWithTitle:@"数据更新" Time:1.5 View:self.view Style:(XFNoticesStyleSuccess)]; return; } else{ YXFAddUserViewController *addUser = [[YXFAddUserViewController alloc]init]; addUser.operateType = 1; //下面的方法是将选中的行的数据存进单例,再传到另一个类里面 [YXFDataFromDataBase shareFromDataBase].nameFromClass = [self.nameArray objectAtIndex:(indexPath.row-1)]; [YXFDataFromDataBase shareFromDataBase].IDFromClass = [self.IDArray objectAtIndex:(indexPath.row-1)]; [YXFDataFromDataBase shareFromDataBase].ageFromClass = [self.ageArray objectAtIndex:(indexPath.row-1)]; NSLog(@"datafromdatabase.nameFromClass==%@",[YXFDataFromDataBase shareFromDataBase].nameFromClass); //跳转到修改页面 [self.navigationController pushViewController:addUser animated:YES]; } }
#import "YXFAddressViewCell.h"
#import <UIKit/UIKit.h> @interface YXFAddressViewCell : UITableViewCell @property (nonatomic, strong) UILabel *nameLabel; @property (nonatomic, strong) UILabel *ageLabel; @property (nonatomic, strong) UILabel *ID; @end
#import "YXFAddressViewCell.m"
#import "YXFAddressViewCell.h" @implementation YXFAddressViewCell - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) { [self p_setupView]; } return self; } - (void)p_setupView { self.nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.contentView.frame) / 3, CGRectGetHeight(self.contentView.frame))]; self.nameLabel.textAlignment = NSTextAlignmentCenter; [self.contentView addSubview:_nameLabel]; self.ageLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.nameLabel.frame), 0, CGRectGetWidth(self.contentView.frame) / 3, CGRectGetHeight(self.contentView.frame))]; self.ageLabel.textAlignment = NSTextAlignmentCenter; [self.contentView addSubview:_ageLabel]; self.ID = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.ageLabel.frame), 0, CGRectGetWidth(self.contentView.frame) / 3, CGRectGetHeight(self.contentView.frame))]; self.ID.textAlignment = NSTextAlignmentCenter; [self.contentView addSubview:_ID]; }
现在运行是没有数据的 , 因为我们还没有添加数据,接下来,我们就来编写添加用户的代码
#import "YXFAddUserViewController.h"
#import <UIKit/UIKit.h> @interface YXFAddUserViewController : UIViewController { NSInteger operateType1;//保存操作类型,0是添加,1是修改 } @property (nonatomic, strong) NSMutableArray *textFieldArray; @property (nonatomic, strong) NSString *dbPath; @property (nonatomic, strong) UITextField *nameTextField; @property (nonatomic, strong) UITextField *ageTextField; @property (nonatomic, strong) UITextField *IDTextField; @property (nonatomic, assign) NSInteger operateType; @end
#import "YXFAddUserViewController.m"
#import "YXFAddUserViewController.h" #import "YXFDataFromDataBase.h" #import "FMDatabase.h" #import "XFNotices.h" @interface YXFAddUserViewController () <UITextFieldDelegate> @end @implementation YXFAddUserViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *path = [doc stringByAppendingPathComponent:@"user.sqlite"]; NSLog(@"path===%@",path); self.dbPath = path; NSArray *array = [NSArray arrayWithObjects:@"姓名",@"年龄",@"ID", nil]; for (int i = 0; i < 3 ; i++) { UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake( 70,i * 40 + 134, 100, 30)]; label.text = [array objectAtIndex:i]; [self.view addSubview:label]; } _nameTextField = [[UITextField alloc]initWithFrame:CGRectMake(150, 138, 100, 30)]; _nameTextField.borderStyle = UITextBorderStyleRoundedRect; _nameTextField.placeholder = @"请输入姓名"; _nameTextField.delegate = self; [self.view addSubview:_nameTextField]; _ageTextField = [[UITextField alloc]initWithFrame:CGRectMake(150, 178, 100, 30)]; _ageTextField.borderStyle = UITextBorderStyleRoundedRect; _ageTextField.placeholder = @"请输入年龄"; _ageTextField.delegate = self; [self.view addSubview:_ageTextField]; _IDTextField = [[UITextField alloc]initWithFrame:CGRectMake(150, 218, 100, 30)]; _IDTextField.borderStyle = UITextBorderStyleRoundedRect; _IDTextField.placeholder = @"请输入ID"; _IDTextField.delegate = self; [self.view addSubview:_IDTextField]; if (_operateType == 1) {//operateType == 1时为修改 _nameTextField.text = [YXFDataFromDataBase shareFromDataBase].nameFromClass; _IDTextField.text = [YXFDataFromDataBase shareFromDataBase].IDFromClass; _ageTextField.text = [YXFDataFromDataBase shareFromDataBase].ageFromClass; _IDTextField.enabled = NO; NSLog(@"datafromdatabase.nameFromClass=%@",[YXFDataFromDataBase shareFromDataBase].nameFromClass); } NSLog(@"operateType==%ld",operateType1); if (_operateType == 0){ UIBarButtonItem *addBtn = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addNewUserInfo)]; self.navigationItem.rightBarButtonItem = addBtn; } if(_operateType == 1){//这里是后来添加的,其实可以放到上面 UIBarButtonItem *addBtn = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(addNewUserInfo)]; self.navigationItem.rightBarButtonItem = addBtn; } } //添加详细信息 - (void)addNewUserInfo { FMDatabase *db = [[FMDatabase alloc]initWithPath:self.dbPath]; if ([db open]) { if (_nameTextField.text.length == 0||_ageTextField.text.length == 0||_IDTextField.text.length == 0){ [XFNotices noticesWithTitle:@"请完成填写信息" Time:1.5 View:self.view Style:(XFNoticesStyleFail)]; }else{ NSLog(@"姓名==%@,年龄==%@,ID==%@",_nameTextField.text,_ageTextField.text,_IDTextField.text); NSString *sql= nil; if (self.operateType == 0){//执行插入操作 sql = @"INSERT INTO USER (name,age,idcode) VALUES (?,?,?) "; }else if(_operateType == 1)//执行更新操作 { sql = @"UPDATE USER SET name = ? , age = ? where idcode = ?"; } BOOL res = [db executeUpdate:sql,_nameTextField.text,_ageTextField.text,_IDTextField.text]; if (!res) { [XFNotices noticesWithTitle:@"数据插入错误" Time:1.5 View:self.view Style:(XFNoticesStyleFail)]; }else{ [XFNotices noticesWithTitle:@"数据插入成功" Time:1.5 View:self.view Style:(XFNoticesStyleFail)]; } } }else{ NSLog(@"数据库打开失败") ; } if (operateType1 == 0)//如果是添加就留在该页,如果是修改就跳回上一页 { [_nameTextField resignFirstResponder]; [_ageTextField resignFirstResponder]; [_IDTextField resignFirstResponder]; _nameTextField.text = @""; _ageTextField.text = @""; _IDTextField.text = @""; [self.navigationController popViewControllerAnimated:YES]; } [db close]; } //让键盘隐藏 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [_nameTextField resignFirstResponder]; [_ageTextField resignFirstResponder]; [_IDTextField resignFirstResponder]; } //页面将要消失的时候执行,将UITextField清空 -(void)viewWillDisappear:(BOOL)animated{ [super viewWillDisappear:YES]; _nameTextField.text = nil; _ageTextField.text = nil; _IDTextField.text = nil; } @end
这个界面就这么多
我们继续创建我们的第三个界面 search 这个界面运用了 UISearchBar一开始我还是不怎么了解,想了超长时间,不过还是弄好了!!
#import "YXFSearchViewController.h"
#import <UIKit/UIKit.h> @interface YXFSearchViewController : UITableViewController @property (nonatomic, strong) NSString *dbpath; /* 用于保存搜索出姓名的结果 */ @property (nonatomic, strong) NSMutableArray *searchResults; /* 用来保存搜索的年龄信息 */ @property (nonatomic, strong) NSMutableArray *searchAgeResults; /* 用来保存搜索的ID信息 */ @property (nonatomic, strong) NSMutableArray *searchIDResult; /* 保存搜索之前的姓名信息 */ @property (nonatomic, strong) NSMutableArray *nameArray; /* 保存搜索之前的年龄信息 */ @property (nonatomic,strong) NSMutableArray *ageArray; /* 保存搜索之前的ID信息 */ @property (nonatomic,strong) NSMutableArray *IDArray; /* 用来保存搜索的年龄信息 */ @property (nonatomic,assign) BOOL searchWasActive; /* 这个好像没用了 */ @property (nonatomic,assign) NSString *savedSearchTerm; @property (nonatomic,retain) NSString *namestr; @property (nonatomic,retain) NSString *agestr; @property (nonatomic,retain) NSString *IDstr; @end
#import "YXFSearchViewController.m"
#import "YXFSearchViewController.h" #import "YXFAddUserViewController.h" #import "YXFAddressViewController.h" #import "FMDatabase.h" #import "YXFDetailViewController.h" @interface YXFSearchViewController () <UISearchBarDelegate,UISearchControllerDelegate> @property (nonatomic, strong) UISearchDisplayController *searchController; @end @implementation YXFSearchViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; //搜索比较复杂,既要初始化UISearchBar,又要初始化UISearchDisplayController,然后还要写UITableViewDelegate里的-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath和-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section方法,还要设置一大堆代理,慢慢往下看 UISearchBar *search = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width -50, 44)]; search.placeholder = @"请输入姓名"; search.autocorrectionType = UITextAutocorrectionTypeNo;//不自动纠错,貌似没啥用 search.autocapitalizationType = UITextAutocapitalizationTypeAllCharacters;//所有字母大写 ,也没啥用 search.showsScopeBar = YES; search.delegate = self;//UISearchBar设置代理 search.keyboardType = UIKeyboardTypeNamePhonePad; self.tableView.tableHeaderView = search; self.tableView.dataSource = self; _searchController = [[UISearchDisplayController alloc]initWithSearchBar:search contentsController:self]; _searchController.active = NO; _searchController.delegate = self;//UISearchDisplayController设置代理 _searchController.searchResultsDelegate=self;//还是代理 _searchController.searchResultsDataSource = self;//有完没完 NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]; NSString *path = [document stringByAppendingPathComponent:@"user.sqlite"]; NSLog(@"path==%@",path); self.dbpath = path; self.tableView.delegate = self;//tableView的代理,为什么这么写,因为这个类是继承UITableView的,要注意!不是继承UIViewController的! self.tableView.dataSource = self; _nameArray = [[NSMutableArray alloc]initWithCapacity:0]; _ageArray = [[NSMutableArray alloc]initWithCapacity:0]; _IDArray= [[NSMutableArray alloc]initWithCapacity:0]; [self getAllDatabase]; [self.tableView reloadData]; } - (void)viewWillAppear:(BOOL)animated { [self.tableView reloadData]; } - (void)getAllDatabase { FMDatabase *db = [FMDatabase databaseWithPath:self.dbpath]; if ([db open]) { NSString *sql = @"SELECT * FROM USER"; FMResultSet *rs = [db executeQuery:sql]; while ([rs next]) { NSString *name = [rs stringForColumn:@"name"]; NSString *age = [rs stringForColumn:@"age"]; NSString *ID = [rs stringForColumn:@"idcode"]; [self.nameArray addObject:name]; [self.ageArray addObject:age]; [self.IDArray addObject:ID]; } self.searchResults = [[NSMutableArray alloc]initWithArray:_nameArray copyItems:YES]; self.searchAgeResults = [[NSMutableArray alloc]initWithArray:_ageArray copyItems:YES]; self.searchIDResult = [[NSMutableArray alloc]initWithArray:_IDArray copyItems:YES]; NSLog(@"search from nameArray==%@",self.nameArray); [db close]; } } #pragma mark - Table view data source - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { NSInteger row = 0; if ([tableView isEqual:self.searchDisplayController.searchResultsTableView]) {//记住这个格式,如果当前的table就是用于显示所搜信息的table的话。因为UISearchDisplayController这货自带一个table row = [self.searchResults count]; }else{ [self.nameArray count]; } return row; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellIdentifier = @"cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; } cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; if ([tableView isEqual:self.searchDisplayController.searchResultsTableView]) { cell.textLabel.text = [_searchResults objectAtIndex:indexPath.row]; // cell.detailTextLabel.text = [NSString stringWithFormat:@"电话:%@",[searchResults objectAtIndex:indexPath.row]];//不知道为什么不显示cell.detailTextLabel.text ,有人知道的话告诉我一下 }else{ cell.textLabel.text = [self.nameArray objectAtIndex:indexPath.row]; } return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { YXFDetailViewController *detailInfo = [[YXFDetailViewController alloc]init]; detailInfo.nameStr = [self.searchResults objectAtIndex:indexPath.row]; detailInfo.ageStr = [self.searchAgeResults objectAtIndex:indexPath.row]; detailInfo.IDsStr = [self.searchIDResult objectAtIndex:indexPath.row]; NSLog(@"self.namestr==%@",self.namestr); NSArray *array = [self.navigationController viewControllers];//先获取视图控制器数组 UINavigationController *nav = [array objectAtIndex:[array count] - 1];//获取当前的导航试图控制器 [nav.navigationController pushViewController:detailInfo animated:YES];//跳转到删除页面 } #pragma mark -UISearchControllerDisplay-//设置搜索范围 //下面注意了,下面的方法是实现搜索功能的,后面两个长得很像的方法是UISearchControllerDisplay代理里的方法,我也搞不懂是干什么用的,他们的格式很固定,大家记住就行了。 - (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope { [self searchBarSearchButtonClicked:self.searchDisplayController.searchBar]; } - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar//从数据库搜索 { FMDatabase *db = [FMDatabase databaseWithPath:self.dbpath]; if ([db open]) { [_searchResults removeAllObjects]; [_searchAgeResults removeAllObjects]; [_searchIDResult removeAllObjects]; NSString *sql = @"SELECT * FROM USER WHERE name like ?"; FMResultSet *rs = [db executeQuery:sql,searchBar.text]; while ([rs next]) { self.namestr = [rs stringForColumn:@"name"]; self.agestr = [rs stringForColumn:@"age"]; self.IDstr = [rs stringForColumn:@"idcode"]; [self.searchResults addObject:_namestr]; [self.searchAgeResults addObject:_agestr]; [self.searchIDResult addObject:_IDstr]; } NSLog(@"searchResults == %@",_searchResults); NSLog(@"searchAgeResults==%@",_searchAgeResults); NSLog(@"searchIDResult==%@",_searchIDResult); NSLog(@"search===%@",searchBar.text); } [db close]; } #pragma mark - #pragma mark UISearchDisplayController Delegate Methods设置代理方法 - (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString { [self filterContentForSearchText:searchString scope: [[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]]; return YES; } - (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption { [self filterContentForSearchText:[self.searchDisplayController.searchBar text] scope: [[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]]; return YES; } @end
在搜索框里面查到我们数据,我们可以点击进入详细界面,那么,我们就来创建详细界面吧,数据库的删除就在这里面实现了!
#import "YXFDetailViewController.h"
#import <UIKit/UIKit.h> @interface YXFDetailViewController : UIViewController @property(nonatomic, strong) NSString *dbpath; @property(nonatomic, strong) NSString *nameStr; @property(nonatomic, strong) NSString *ageStr; @property(nonatomic, strong) NSString *IDsStr; @end
#import "YXFDetailViewController.m"
#import "YXFDetailViewController.h" #import "FMDatabase.h" #import "XFNotices.h" @interface YXFDetailViewController () @end @implementation YXFDetailViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; self.title = @"详细信息"; NSArray *array = [NSArray arrayWithObjects:@"姓名:",@"年龄:",@"ID:", nil]; NSArray *array2 = [NSArray arrayWithObjects:self.nameStr,self.ageStr,self.IDsStr, nil]; for (int i = 0; i < 3 ; i++) { UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake( 70,i * 40 + 134, 100, 30)]; label.text = [array objectAtIndex:i]; [self.view addSubview:label]; UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(140, i * 40 +135, 100, 30)]; label2.text = [array2 objectAtIndex:i]; [self.view addSubview:label2]; } NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]; NSString *path = [document stringByAppendingPathComponent:@"USER.sqlite"]; self.dbpath = path; UIBarButtonItem *deleteButton = [[UIBarButtonItem alloc]initWithTitle:@"删除" style:UIBarButtonItemStyleDone target:self action:@selector(deleteFromDatabase)]; self.navigationItem.rightBarButtonItem = deleteButton; } - (void)deleteFromDatabase//从数据库删除信息 { FMDatabase *db = [FMDatabase databaseWithPath:self.dbpath]; if ([db open]) { NSString *sql = @"DELETE FROM USER WHERE name = ? and age = ? and idcode = ?"; if (self.nameStr.length != 0&&self.ageStr.length != 0&&self.IDsStr.length !=0){ BOOL rs = [db executeUpdate:sql,self.nameStr,self.ageStr,self.IDsStr]; //后面跟的三个参数就是sql语句里的三个问号对应 if (rs) { [XFNotices noticesWithTitle:@"删除成功" Time:1 View:self.view Style:(XFNoticesStyleSuccess)]; [self.navigationController popViewControllerAnimated:YES]; }else{ [XFNotices noticesWithTitle:@"删除失败" Time:1 View:self.view Style:(XFNoticesStyleFail)]; } } } [db close]; } @end
好了 都完成了,接下来 运行编译 看看效果吧
上面,我已经贴上demo 的地址了,但是还是希望刚刚接触的朋友自己写一遍,要是碰到什么 bug 希望能告诉我,我及时更正错误!