作者唯一QQ:228544117。。。。。
=========后面的都要新建一个文章
AppDelegate.h 引入 viewcontroller
AppDelegate.m
//头文件
#import "ViewController.h"
#import "AddUserInfo.h"
#import "SearchInfo.h"
//代码
//application:(UIApplication *)application didFinishLaunchingWithOptions
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch. self.viewController = [[ViewController alloc] init]; //因为有三个tabBarItem,我把系统默认的viewController放在了第一个,然后再新建两个继承自UIViewController的类AddUserInfo和SearchInfo UINavigationController *viewController = [[UINavigationController alloc]initWithRootViewController:self.viewController]; viewController.tabBarItem = [[UITabBarItem alloc]initWithTabBarSystemItem:UITabBarSystemItemContacts tag:101]; //将viewController初始化为第一个tabBarItem AddUserInfo *adduserViewController = [[AddUserInfo alloc]init]; adduserViewController.title = @"添加用户信息"; adduserViewController.tabBarItem = [[UITabBarItem alloc]initWithTabBarSystemItem:UITabBarSystemItemTopRated tag:102]; //将adduserViewController初始化为第二个tabBarItem SearchInfo *searchViewController = [[SearchInfo alloc]init]; searchViewController.tabBarItem = [[UITabBarItem alloc]initWithTabBarSystemItem:UITabBarSystemItemSearch tag:103]; searchViewController.title = @"搜索信息"; //将searchViewController初始化为第三个tabBarItem,现在已经准备了UITabBarController上的三个tabBarItem了,但是每一个tabBarItem都需要放到UINavigationController上来控制视图,在初始化两个UINavigationController,还有一个在上面。 UINavigationController *nav1= [[UINavigationController alloc]initWithRootViewController:adduserViewController]; UINavigationController *nav2 = [[UINavigationController alloc]initWithRootViewController:searchViewController]; NSArray *ViewControllerArray = [[NSArray alloc]initWithObjects:viewController,nav1,nav2, nil]; // 将三个UINavigationController添加到一个数组里,tabBarItem已经搞定了,但是主要的UITabBarController我们现在来初始化。 UITabBarController *tabBarController = [[UITabBarController alloc]init]; //注意这里的用法,tabBarController.viewControllers是tabBarController的一个数组类型的属性,它存放的是UINavigationController tabBarController.viewControllers = ViewControllerArray; tabBarController.selectedIndex = 0;//初始显示第一个tabBarItem tabBarController.delegate = self;//别忘了设置代理,在头文件里要加上这两个
self.window.rootViewController = tabBarController;
[self.window makeKeyAndVisible];
return YES;
}
========================================================
//viewcontroller.h
#import "FMDatabase.h"#import "FMDatabaseQueue.h"@class dataFromDataBase;@interface ViewController : UIViewController{
}
@property (nonatomic, retain) NSString * dbPath;
@property (nonatomic, retain) NSMutableArray *nameArray;
@property (nonatomic, retain) NSMutableArray *phoneArray;
@property (nonatomic, retain) NSMutableArray *IDArray;
@property (nonatomic, retain) UITableView *table;
- (void)createTable;
@end
@interface dataFromDataBase : NSObject {//新建一个类,专门用于保存数据
@private
NSString *nameFromClass;
NSString *phoneFromClass;
NSString *IDFromClass;
NSMutableArray *nameArrayFromClass;
}
+(dataFromDataBase*)shareFromDataBase;//神奇的单例
@property(retain,nonatomic) NSString *nameFromClass;
@property(retain,nonatomic)NSString *phoneFromClass;
@property(retain,nonatomic)NSString *IDFromClass;
@property(retain,nonatomic)NSMutableArray *nameArrayFromClass;
@end
=====================================================
//viewcontroller.m
#import "AddUserInfo.h"
@implementation ViewController
@synthesize dbPath;
@synthesize nameArray,phoneArray,IDArray;
@synthesize table;
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = @"通讯录";
UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
tableView.delegate = self;
tableView.dataSource = self;
self.table = tableView;
[self.view addSubview:tableView];
UIBarButtonItem *refreshBtn = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(modifyDatabase)];
self.navigationItem.rightBarButtonItem = refreshBtn;
}
#pragma mark -tableview-
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// NSString *CustomIdentifier = [NSString stringWithFormat:@"cell%d",indexPath.row];
static NSString *CustomIdentifier = @"cell";
// UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CustomIdentifier];
UITableViewCell *cell = nil;
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CustomIdentifier];
}
// while ([cell.contentView.subviews lastObject] != nil){
[(UIView*)[cell.contentView.subviews lastObject]removeFromSuperview];//当再次刷新的时候会自动添加新的cell,出现叠加情况,用这种方法可以去掉上一次添加的cell.contentView.subviews
if (indexPath.row == 0)//这里注意,因为第一行不显示数据,所以做个判断
cell.selectionStyle = UITableViewCellSelectionStyleNone;
if (indexPath.row > 0) {//从第二行开始显示数据
// cell.textLabel.text = [dataArray objectAtIndex:(indexPath.row - 1)];//注意这里是从indexPath.row - 1行开始
UILabel *nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(0+40, 10, 70, 30)];
UILabel *phoneLabel = [[UILabel alloc]initWithFrame:CGRectMake(90+40, 10, 70, 30)];
UILabel *IDLabel = [[UILabel alloc]initWithFrame:CGRectMake(180+40, 10, 70, 30)];
nameLabel.text = [self.nameArray objectAtIndex:(indexPath.row-1)];
IDLabel.text = [self.IDArray objectAtIndex:(indexPath.row-1)];
phoneLabel.text = [self.phoneArray objectAtIndex:(indexPath.row-1)];
[cell.contentView addSubview:nameLabel];
[cell.contentView addSubview:IDLabel];
[cell.contentView addSubview:phoneLabel];
} else
{
for (int i = 0; i < 3; i ++) {
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(90 * i + 40, 10, 70 , 30)];
NSArray *array = [NSArray arrayWithObjects:@"姓名",@"电话",@"ID", nil];
label.text = [array objectAtIndex:i];
label.backgroundColor = [UIColor clearColor];
[cell.contentView addSubview:label];
label = nil;
}
}
// }
return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [nameArray count] + 1;//注意这里,因为第一行不显示数据,返回要加一行
}
- (NSIndexPath*)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row == 0) {
return nil;//让第一行不能点击
}
else
return indexPath;
}
- (void)createTable//创建数据库中表的方法,利用封装好的库很简单
{
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:self.dbPath]) {
NSLog(@"表不存在,创建表");
FMDatabase *db =[FMDatabase databaseWithPath:self.dbPath];
if ([db open]) {
NSString *sql = @"CREATE TABLE 'USER'('id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 'name' VARCHAR(20),'phone' 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.dbPath];
if ([db open]) {
NSString *sql = @"SELECT * FROM USER";
FMResultSet *rs = [db executeQuery:sql];
while ([rs next]) {
NSString *name = [rs stringForColumn:@"name"];
NSString *phone = [rs stringForColumn:@"phone"];
NSString *ID = [rs stringForColumn:@"idcode"];
[self.nameArray addObject:name];
[self.phoneArray addObject:phone];
[self.IDArray addObject:ID];
}
[[dataFromDataBase shareFromDataBase].nameArrayFromClass arrayByAddingObjectsFromArray:self.nameArray];
NSLog(@"self.nameArray==%@",self.nameArray);
[db close];
[table reloadData];
}
}
- (void)modifyDatabase//选中相应的行,进入更新界面,注意这里没有对数据库进行操作
{
NSIndexPath *indexPath = [self.table indexPathForSelectedRow];
if (indexPath == nil) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
message:@"请选择要更新的项"
delegate:self
cancelButtonTitle:@"好"
otherButtonTitles:nil];
[alert show];
return;
}
else{
AddUserInfo *modify = [[AddUserInfo alloc]init]; modify.operateType = 1;
//下面的方法是将选中的行的数据存进单例,再传到另一个类里面
[dataFromDataBase shareFromDataBase].nameFromClass = [self.nameArray objectAtIndex:(indexPath.row-1)];
[dataFromDataBase shareFromDataBase].IDFromClass = [self.IDArray objectAtIndex:(indexPath.row-1)];
[dataFromDataBase shareFromDataBase].phoneFromClass = [self.phoneArray objectAtIndex:(indexPath.row-1)];
NSLog(@"datafromdatabase.nameFromClass==%@",[dataFromDataBase shareFromDataBase].nameFromClass);
[self.navigationController pushViewController:modify animated:YES];//跳转到修改页面
}
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *path = [document stringByAppendingPathComponent:@"USER.sqlite"];
self.dbPath = path;
//注意以上三句话是获取数据库路径必不可少的,在viewDidload之前就已经准备好了
nameArray = [[NSMutableArray alloc]init];
phoneArray = [[NSMutableArray alloc]init];
IDArray = [[NSMutableArray alloc]init];
[self createTable];
[self getAllDatabase];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
@end
@implementation dataFromDataBase//这个类专门用来保存数据
@synthesize nameFromClass,phoneFromClass,IDFromClass;
@synthesize nameArrayFromClass;
static dataFromDataBase *sharedInstance = nil;
+(dataFromDataBase*)shareFromDataBase//伟大的单例,
{
if (sharedInstance == nil) {
sharedInstance = [[dataFromDataBase alloc]init];
}
return sharedInstance;
}
- (id)init {
self = [super init];
if (self) {
nameFromClass = @"";
phoneFromClass = @"";
IDFromClass = @"";
nameArrayFromClass = [[NSMutableArray alloc]initWithCapacity:0];
}
return self;
}
- (void)dealloc {
if (nameFromClass!= nil){
}
if (phoneFromClass!=nil){
}
if (IDFromClass != nil){
}
if (nameArrayFromClass != nil) {
}
}
@end
===================================================
//AddUserInfo.h
#import "ViewController.h"@interface AddUserInfo : UIViewController{
int operateType;//保存操作类型,0是添加,1是修改
}
- (void)createTable;
@property (retain,nonatomic)NSMutableArray *textFieldArray;
@property (retain,nonatomic)NSString *dbPath;
@property (retain,nonatomic)UITextField *nameTextField;
@property (retain,nonatomic)UITextField *phoneTextField;
@property (retain,nonatomic)UITextField *IDTextField;
@property (nonatomic,assign)int operateType;
@end
================================================
//AddUserInfo.m
#import "FMDatabase.h"
#import "FMDatabaseQueue.h"
#import "UserDetailInfo.h"
@implementation AddUserInfo
@synthesize textFieldArray;
@synthesize dbPath;
@synthesize nameTextField;
@synthesize phoneTextField;
@synthesize IDTextField;
@synthesize operateType;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
textFieldArray = [[NSMutableArray alloc]init];
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
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 + 34, 100, 30)];
label.text = [array objectAtIndex:i];
[self.view addSubview:label];
}
nameTextField = [[UITextField alloc]initWithFrame:CGRectMake(150, 100, 100, 30)];
nameTextField.borderStyle = UITextBorderStyleRoundedRect;
nameTextField.placeholder = @"请输入姓名";
nameTextField.delegate = self;
[self.view addSubview:nameTextField];
phoneTextField = [[UITextField alloc]initWithFrame:CGRectMake(150, 150, 100, 30)];
phoneTextField.borderStyle = UITextBorderStyleRoundedRect;
phoneTextField.placeholder = @"请输入电话";
phoneTextField.delegate = self;
[self.view addSubview:phoneTextField];
IDTextField = [[UITextField alloc]initWithFrame:CGRectMake(150, 200, 100, 30)];
IDTextField.borderStyle = UITextBorderStyleRoundedRect;
IDTextField.placeholder = @"请输入ID";
IDTextField.delegate = self;
[self.view addSubview:IDTextField];
if (operateType == 1) {//operateType == 1时为修改
nameTextField.text = [dataFromDataBase shareFromDataBase].nameFromClass;
IDTextField.text = [dataFromDataBase shareFromDataBase].IDFromClass;
phoneTextField.text = [dataFromDataBase shareFromDataBase].phoneFromClass;
IDTextField.enabled = NO;
NSLog(@"datafromdatabase.nameFromClass=%@",[dataFromDataBase shareFromDataBase].nameFromClass);
}
NSLog(@"operateType==%d",operateType);
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;
}
// Do any additional setup after loading the view from its nib.
}
- (void)addNewUserInfo//添加用户信息的方法,用FMDB封装好的方法
{
FMDatabase *db = [[FMDatabase alloc]initWithPath:self.dbPath];
NSString *mes = nil;
if ([db open]) {
if (nameTextField.text.length == 0||phoneTextField.text.length == 0||IDTextField.text.length == 0){
mes = @"请完成填写信息";
}else{
NSLog(@"姓名==%@,电话==%@,ID==%@",nameTextField.text,phoneTextField.text,IDTextField.text);
NSString *sql= nil;
if (operateType == 0){//执行插入操作
sql = @"INSERT INTO USER (name,phone,idcode) VALUES (?,?,?) ";
}else if(operateType == 1)//执行更新操作
{
sql = @"UPDATE USER SET name = ? , phone = ? where idcode = ?";
NSLog(@"有没有执行?");
}
BOOL res = [db executeUpdate:sql,nameTextField.text,phoneTextField.text,IDTextField.text];
if (!res) {
NSLog(@"error to insert data");
mes = @"数据插入错误";
}else{
NSLog(@"insert succeed");
mes = @"数据插入成功";
}
}
}else{
NSLog(@"数据库打开失败") ;
}
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:mes delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[alert setTag:101];
alert.delegate = self;
[alert show];
[db close];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (alertView.tag == 101 && buttonIndex == 0) {
if (operateType == 0)//如果是添加就留在该页,如果是修改就跳回上一页
{
[nameTextField resignFirstResponder];
[phoneTextField resignFirstResponder];
[IDTextField resignFirstResponder];
nameTextField.text = @"";
phoneTextField.text = @"";
IDTextField.text = @"";
}else{
[self.navigationController popViewControllerAnimated:YES];
}
}
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[nameTextField resignFirstResponder];
[phoneTextField resignFirstResponder];
[IDTextField resignFirstResponder];
}//让键盘隐藏
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:YES];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
-(void)viewWillDisappear:(BOOL)animated//页面将要消失的时候执行,将UITextField清空
{
[super viewWillDisappear:YES];
nameTextField.text = nil;
phoneTextField.text = nil;
IDTextField.text = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
@end
================================================
//SearchInfo.h
@interface SearchInfo : UITableViewController{
UISearchDisplayController *searchController;
NSString *namestr;
NSString *phonestr;
NSString *IDstr;
}
@property (retain,nonatomic)NSString *dbpath;
@property (retain,nonatomic)NSMutableArray *searchResults;//用于保存搜索出姓名的结果
@property (retain,nonatomic)NSMutableArray *searchPhoneResults;//用来保存搜索的电话信息
@property (retain,nonatomic)NSMutableArray *searchIDResult;//用来保存搜索的ID信息
@property (retain,nonatomic)NSMutableArray *nameArray;//保存搜索之前的姓名信息
@property (retain,nonatomic)NSMutableArray *phoneArray;//保存搜索之前的电话信息
@property (retain,nonatomic)NSMutableArray *IDArray;//保存搜索之前的ID信息
@property (nonatomic,assign)BOOL searchWasActive;
@property (nonatomic,assign)NSString *savedSearchTerm;//这个好像没用了
@property (nonatomic,retain)NSString *namestr;
@property (nonatomic,retain)NSString*phonestr;
@property (nonatomic,retain)NSString*IDstr;
- (void)getAllDatabase;
@end
================================================
//SearchInfo.m
#import "FMDatabase.h"
#import "ViewController.h"
#import "UserDetailInfo.h"
@implementation SearchInfo
@synthesize dbpath;
@synthesize searchResults,searchPhoneResults,searchIDResult;
@synthesize nameArray,phoneArray,IDArray;
@synthesize searchWasActive;
@synthesize savedSearchTerm;
@synthesize namestr,phonestr,IDstr;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
//搜索比较复杂,既要初始化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];
phoneArray = [[NSMutableArray alloc]initWithCapacity:0];
IDArray= [[NSMutableArray alloc]initWithCapacity:0];
[self getAllDatabase];
[self.tableView reloadData];
// Do any additional setup after loading the view from its nib.
}
- (void)viewWillAppear:(BOOL)animated
{
self.searchWasActive = [self.searchDisplayController isActive];
if (self.searchDisplayController.searchBar != 0)
{
self.searchDisplayController.searchBar.text = nil;
[self.searchDisplayController.searchBar resignFirstResponder];
[self.searchDisplayController setActive:NO];//在进入搜索页面之前将其设置为不活动,大家可以试试改成活动看看是什么样
}
}
- (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 *phone = [rs stringForColumn:@"phone"];
NSString *ID = [rs stringForColumn:@"idcode"];
[self.nameArray addObject:name];
[self.phoneArray addObject:phone];
[self.IDArray addObject:ID];
}
self.searchResults = [[NSMutableArray alloc]initWithArray:nameArray copyItems:YES];
self.searchPhoneResults = [[NSMutableArray alloc]initWithArray:phoneArray copyItems:YES];
self.searchIDResult = [[NSMutableArray alloc]initWithArray:IDArray copyItems:YES];
NSLog(@"search from nameArray==%@",self.nameArray);
[db close];
}
}
#pragma mark -tableview-
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// self.tableView = tableView;
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;
}
-(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;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UserDetailInfo *detailInfo = [[UserDetailInfo alloc]init];
detailInfo.nameStr = [self.searchResults objectAtIndex:indexPath.row];
detailInfo.phoneStr = [self.searchPhoneResults 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];
[searchPhoneResults 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.phonestr = [rs stringForColumn:@"phone"];
self.IDstr = [rs stringForColumn:@"idcode"];
[self.searchResults addObject:namestr];
[self.searchPhoneResults addObject:phonestr];
[self.searchIDResult addObject:IDstr];
}
NSLog(@"searchResults == %@",searchResults);
NSLog(@"searchPhoneResults==%@",searchPhoneResults);
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 to cause the search result table view to be reloaded.
return YES;
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption
{
[self filterContentForSearchText:[self.searchDisplayController.searchBar text] scope:
[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];
// Return YES to cause the search result table view to be reloaded.
return YES;
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
@end
===============================
//UserDetailInfo.h
@interface UserDetailInfo : UIViewController{
}
@property(retain,nonatomic)NSString *dbpath;
@property(retain,nonatomic)NSString *nameStr;
@property(retain,nonatomic)NSString *phoneStr;
@property(retain,nonatomic)NSString *IDsStr;
@end
====================================
//UserDetailInfo.m
#import "FMDatabase.h"
@implementation UserDetailInfo
@synthesize dbpath;
@synthesize nameStr,phoneStr,IDsStr;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.title = @"详细信息";
NSArray *array = [NSArray arrayWithObjects:@"姓名:",@"电话:",@"ID:", nil];
NSArray *array2 = [NSArray arrayWithObjects:self.nameStr,self.phoneStr,self.IDsStr, nil];
for (int i = 0; i < 3 ; i++)
{
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake( 70,i * 40 + 34, 100, 30)];
label.text = [array objectAtIndex:i];
[self.view addSubview:label];
UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(140, i * 40 +35, 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];
NSString *mes = nil;
if ([db open]) {
NSString *sql = @"DELETE FROM USER WHERE name = ? and phone = ? and idcode = ?";
if (self.nameStr.length != 0&&self.phoneStr.length != 0&&self.IDsStr.length !=0){
BOOL rs = [db executeUpdate:sql,self.nameStr,self.phoneStr,self.IDsStr]; //后面跟的三个参数就是sql语句里的三个问号对应
if (rs) {
mes = @"删除成功";
}else{
mes = @"删除失败";
}
}
}
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:mes delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
alert.delegate = self;//别忘了代理
[alert show];
[db close];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if ( buttonIndex == 0) {
[self.navigationController popViewControllerAnimated:YES];
NSLog(@"点击了删除成功");
}
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:YES];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
@end