FMDB

作者唯一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,我把系統(tǒng)默認(rèn)的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凿跳,現(xiàn)在已經(jīng)準(zhǔn)備了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添加到一個數(shù)組里,tabBarItem已經(jīng)搞定了疆栏,但是主要的UITabBarController我們現(xiàn)在來初始化曾掂。? ? UITabBarController *tabBarController = [[UITabBarController alloc]init];? ? //注意這里的用法,tabBarController.viewControllers是tabBarController的一個數(shù)組類型的屬性壁顶,它存放的是UINavigationController? ? tabBarController.viewControllers = ViewControllerArray;? ? tabBarController.selectedIndex = 0;//初始顯示第一個tabBarItem? ? tabBarController.delegate = self;//別忘了設(shè)置代理珠洗,在頭文件里要加上這兩個

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 {//新建一個類,專門用于保存數(shù)據(jù)

@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];//當(dāng)再次刷新的時候會自動添加新的cell若专,出現(xiàn)疊加情況许蓖,用這種方法可以去掉上一次添加的cell.contentView.subviews

if (indexPath.row == 0)//這里注意,因為第一行不顯示數(shù)據(jù)调衰,所以做個判斷

cell.selectionStyle = UITableViewCellSelectionStyleNone;

if (indexPath.row > 0) {//從第二行開始顯示數(shù)據(jù)

//? ? ? ? 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;//注意這里膊爪,因為第一行不顯示數(shù)據(jù),返回要加一行

}

- (NSIndexPath*)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

if (indexPath.row == 0) {

return nil;//讓第一行不能點擊

}

else

return indexPath;

}

- (void)createTable//創(chuàng)建數(shù)據(jù)庫中表的方法嚎莉,利用封裝好的庫很簡單

{

NSFileManager *fileManager = [NSFileManager defaultManager];

if (![fileManager fileExistsAtPath:self.dbPath]) {

NSLog(@"表不存在米酬,創(chuàng)建表");

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//從數(shù)據(jù)庫中獲得所有數(shù)據(jù)

{

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//選中相應(yīng)的行,進(jìn)入更新界面萝喘,注意這里沒有對數(shù)據(jù)庫進(jìn)行操作

{

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;

//下面的方法是將選中的行的數(shù)據(jù)存進(jìn)單例淮逻,再傳到另一個類里面

[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];//跳轉(zhuǎn)到修改頁面

}

}

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

//注意以上三句話是獲取數(shù)據(jù)庫路徑必不可少的,在viewDidload之前就已經(jīng)準(zhǔn)備好了

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//這個類專門用來保存數(shù)據(jù)

@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){//執(zhí)行插入操作

sql = @"INSERT INTO USER (name,phone,idcode) VALUES (?,?,?) ";

}else if(operateType == 1)//執(zhí)行更新操作

{

sql = @"UPDATE USER? SET name = ? , phone = ? where idcode = ?";

NSLog(@"有沒有執(zhí)行?");

}

BOOL res = [db executeUpdate:sql,nameTextField.text,phoneTextField.text,IDTextField.text];

if (!res) {

NSLog(@"error to insert data");

mes = @"數(shù)據(jù)插入錯誤";

}else{

NSLog(@"insert succeed");

mes = @"數(shù)據(jù)插入成功";

}

}

}else{

NSLog(@"數(shù)據(jù)庫打開失敗") ;

}

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//頁面將要消失的時候執(zhí)行桨啃,將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;//用于保存搜索出姓名的結(jié)果

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

//搜索比較復(fù)雜,既要初始化UISearchBar檬输,又要初始化UISearchDisplayController照瘾,然后還要寫UITableViewDelegate里的-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath和-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section方法,還要設(shè)置一大堆代理丧慈,慢慢往下看

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設(shè)置代理

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設(shè)置代理

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];//在進(jìn)入搜索頁面之前將其設(shè)置為不活動瘩将,大家可以試試改成活動看看是什么樣

}

}

- (void)getAllDatabase//要重新獲取數(shù)據(jù)庫信息,因為執(zhí)行完刪除之后數(shù)據(jù)庫變了

{

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]) {//記住這個格式姿现,如果當(dāng)前的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];//先獲取視圖控制器數(shù)組

UINavigationController *nav = [array objectAtIndex:[array count] - 1];//獲取當(dāng)前的導(dǎo)航試圖控制器

[nav.navigationController pushViewController:detailInfo animated:YES];//跳轉(zhuǎn)到刪除頁面

}

#pragma mark -UISearchControllerDisplay-//設(shè)置搜索范圍

//下面注意了,下面的方法是實現(xiàn)搜索功能的,后面兩個長得很像的方法是UISearchControllerDisplay代理里的方法磷醋,我也搞不懂是干什么用的庙曙,他們的格式很固定,大家記住就行了。

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope

{

[self searchBarSearchButtonClicked:self.searchDisplayController.searchBar];

}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar//從數(shù)據(jù)庫搜索

{

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設(shè)置代理方法

- (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 = @"詳細(xì)信息";

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//從數(shù)據(jù)庫刪除信息

{

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]; //后面跟的三個參數(shù)就是sql語句里的三個問號對應(yīng)

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












最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子镐依,更是在濱河造成了極大的恐慌,老刑警劉巖天试,帶你破解...
    沈念sama閱讀 206,968評論 6 482
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件槐壳,死亡現(xiàn)場離奇詭異,居然都是意外死亡喜每,警方通過查閱死者的電腦和手機务唐,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,601評論 2 382
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來带兜,“玉大人枫笛,你說我怎么就攤上這事「照眨” “怎么了刑巧?”我有些...
    開封第一講書人閱讀 153,220評論 0 344
  • 文/不壞的土叔 我叫張陵,是天一觀的道長无畔。 經(jīng)常有香客問我啊楚,道長,這世上最難降的妖魔是什么浑彰? 我笑而不...
    開封第一講書人閱讀 55,416評論 1 279
  • 正文 為了忘掉前任恭理,我火速辦了婚禮,結(jié)果婚禮上郭变,老公的妹妹穿的比我還像新娘蚯斯。我一直安慰自己薄风,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 64,425評論 5 374
  • 文/花漫 我一把揭開白布拍嵌。 她就那樣靜靜地躺著,像睡著了一般循诉。 火紅的嫁衣襯著肌膚如雪横辆。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,144評論 1 285
  • 那天茄猫,我揣著相機與錄音狈蚤,去河邊找鬼。 笑死划纽,一個胖子當(dāng)著我的面吹牛脆侮,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播勇劣,決...
    沈念sama閱讀 38,432評論 3 401
  • 文/蒼蘭香墨 我猛地睜開眼靖避,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了比默?” 一聲冷哼從身側(cè)響起幻捏,我...
    開封第一講書人閱讀 37,088評論 0 261
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎命咐,沒想到半個月后篡九,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 43,586評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡醋奠,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,028評論 2 325
  • 正文 我和宋清朗相戀三年榛臼,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片窜司。...
    茶點故事閱讀 38,137評論 1 334
  • 序言:一個原本活蹦亂跳的男人離奇死亡沛善,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出例证,到底是詐尸還是另有隱情路呜,我是刑警寧澤,帶...
    沈念sama閱讀 33,783評論 4 324
  • 正文 年R本政府宣布织咧,位于F島的核電站胀葱,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏笙蒙。R本人自食惡果不足惜抵屿,卻給世界環(huán)境...
    茶點故事閱讀 39,343評論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望捅位。 院中可真熱鬧轧葛,春花似錦搂抒、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,333評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至衷笋,卻和暖如春芳杏,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背辟宗。 一陣腳步聲響...
    開封第一講書人閱讀 31,559評論 1 262
  • 我被黑心中介騙來泰國打工爵赵, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人泊脐。 一個月前我還...
    沈念sama閱讀 45,595評論 2 355
  • 正文 我出身青樓空幻,卻偏偏與公主長得像,于是被迫代替她去往敵國和親容客。 傳聞我的和親對象是個殘疾皇子秕铛,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 42,901評論 2 345

推薦閱讀更多精彩內(nèi)容