Application => Single View Application => Next
Product Name = ContactLite, Devices = iPhone, Use Storyboards, Use Automatic Reference Counting
เลือกไปที่ TARGETS => Build Pharses => “+”
เปิดไฟล์ Contact.h
#import <Foundation/Foundation.h>
@interface Contact : NSObject{ NSString *pkId;
NSString *name; NSString *email; }
@property(strong, nonatomic)NSString *name; @property(strong, nonatomic)NSString *email; @property(strong, nonatomic)NSString *pkId; @end เปิดไฟล์ Contact.m #import "Contact.h" @implementation Contact @synthesize pkId,name,email; @end
วาง Navigation Bar, Table View, Table View Cell และ Bar Button Item ตาม ลําดับลงบนรูปด้านล่างนี้
คลิกไปที่ปุ่มตามรูปด้านล่าง “Item” แล้วไปที่ไอคอน Attribute เปลี่ยนค่า Identifier = Add
เลือกไปคลิกที่ Table View Cell ตามรูปด้านล่างนี้ แล้วไปเปลี่ยนค่าของ Style = Subtitle, Identifier = Cell
เปิดไฟล์ ViewController.h ขึ้นมา
#import <UIKit/UIKit.h> #import "sqlite3.h" #import "Contact.h" @interface ViewController : UIViewController<UITableViewDataSource, UITableViewDelegate> { NSArray *dataList; }@property (weak, nonatomic) IBOutlet UINavigationItem
*navItem;
@property (weak, nonatomic) IBOutlet UITableView
*tableV;
@property (nonatomic, retain) NSArray *dataList;
@property (strong, nonatomic) NSString *databasePath; @property (nonatomic) sqlite3 *contactDB;
-(void)setupDatabase; -(void)loadDatabase;
-(void)deleteContact:(NSString *)pkId; @end
เปิดไฟล์ ViewController.m ขึ้นมา
#import "ViewController.h" #import "SaveViewController.h" @interface ViewController () @end @implementation ViewController @synthesize dataList, tableV;@synthesize databasePath, contactDB; @synthesize navItem;
-(void)setupDatabase {
// Get the documents directory NSArray *dirPaths =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *docsDir = dirPaths[0];
// Build the path to the database file databasePath = [[NSString alloc]
initWithString: [docsDir
stringByAppendingPathComponent: @"contacts.db"]]; NSFileManager *filemgr = [NSFileManager
defaultManager];
if ([filemgr fileExistsAtPath: databasePath] == NO) {
const char *dbpath = [databasePath UTF8String]; if (sqlite3_open(dbpath, &contactDB) ==
SQLITE_OK) {
char *errMsg;
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, EMAIL TEXT)";
if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
NSLog(@"Failed to create table"); }
} }}
เปิดไฟล์ ViewController.m - (ต่อ)
-(void)loadDatabase{
NSMutableArray *data = [NSMutableArray array]; sqlite3_stmt *statement;
NSString *querySQL = @"SELECT id, name, email FROM contacts";
const char *query_stmt = [querySQL UTF8String]; const char *dbpath = [databasePath UTF8String]; if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK) {
sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL);
while (sqlite3_step(statement) == SQLITE_ROW) {
NSString *Id = [[NSString alloc]initWithUTF8String:(const char *)
sqlite3_column_text(statement, 0)]; NSString *name = [[NSString alloc]initWithUTF8String:(const char *)
sqlite3_column_text(statement, 1)];
NSString *email = [[NSString alloc]initWithUTF8String:(const char *)
sqlite3_column_text(statement, 2)];
Contact *row = [[Contact alloc] init]; row.pkId = Id;
row.name = name; row.email = email;
[data addObject:row]; }
dataList = [NSMutableArray arrayWithArray:data]; sqlite3_finalize(statement);
} }
เปิดไฟล์ ViewController.m - (ต่อ)
- (void)viewDidLoad{
[super viewDidLoad];
navItem.leftBarButtonItem = self.editButtonItem; [self setupDatabase]; [self loadDatabase]; } -(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:YES]; [self setupDatabase]; [self loadDatabase]; [tableV reloadData]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated. }
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return dataList.count; }
เปิดไฟล์ ViewController.m - (ต่อ)
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellId = @"Cell"; UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:cellId];
if (cell == nil){
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:cellId]; }
Contact *row = (Contact *)[dataList
objectAtIndex:indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:@"%@-%@"
, row.pkId , row.name]; cell.detailTextLabel.text = row.email;
return cell;
เปิดไฟล์ ViewController.m - (ต่อ)
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle ==
UITableViewCellEditingStyleDelete) {
Contact *row = [dataList
objectAtIndex:indexPath.row];
NSMutableArray *array = [NSMutableArray arrayWithArray:dataList];
[array removeObject:row]; dataList = array;
[self deleteContact:row.pkId];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationAutomatic]; }
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender: (id)sender{ SaveViewController *vc = (SaveViewController *)segue.destinationViewController; vc.databasePath = self.databasePath; vc.contactDB = self.contactDB; } -(void)setEditing:(BOOL)editing animated:(BOOL)animated {
[super setEditing:editing animated:animated]; [tableV setEditing:editing animated:animated]; }
เปิดไฟล์ ViewController.m - (ต่อ)
-(UITableViewCellEditingStyle)tableView:(UITableView
*)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath { if (tableV.editing) { return UITableViewCellEditingStyleDelete; } return UITableViewCellEditingStyleNone; }
-(void)deleteContact:(NSString *)pkId {
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String]; if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK) {
NSString *SQL = @"DELETE FROM CONTACTS WHERE ID= \"%@\"";
NSString *deleteSQL = [NSString stringWithFormat:SQL, pkId];
const char *delete_stmt = [deleteSQL UTF8String]; sqlite3_prepare_v2(contactDB, delete_stmt,-1, &statement, NULL);
if (sqlite3_step(statement) != SQLITE_DONE) {
NSLog(@"DELETE FAILED"); } sqlite3_finalize(statement); sqlite3_close(contactDB); } } @end
ตั้งค่า Class = SaveViewController และ Subclass of = UIViewController
เปิดไฟล์ SaveViewController.h
#import <UIKit/UIKit.h> #import "sqlite3.h" @interface SaveViewController : UIViewController<UITextFieldDelegate> - (IBAction)doSaveClick:(id)sender;@property (weak, nonatomic) IBOutlet UITextField *tfName; @property (weak, nonatomic) IBOutlet UITextField
*tfEmail;
@property (strong, nonatomic) NSString *databasePath; @property (nonatomic) sqlite3 *contactDB;
เปิดไฟล์ SaveViewController.m
#import "SaveViewController.h"@interface SaveViewController () @end
@implementation SaveViewController @synthesize tfName, tfEmail;
@synthesize databasePath, contactDB;
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder]; return YES;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle: (NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil
bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad];
! // Do any additional setup after loading the view. [tfName becomeFirstResponder];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated. }
- (IBAction)doSaveClick:(id)sender { sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String]; if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK) {
NSString *SQL = @"INSERT INTO CONTACTS (name, email) VALUES (\"%@\",\"%@\")";
NSString *insertSQL = [NSString
stringWithFormat:SQL, tfName.text, tfEmail.text];
const char *insert_stmt = [insertSQL UTF8String]; sqlite3_prepare_v2(contactDB, insert_stmt,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE) {
[self dismissViewControllerAnimated:YES
completion:nil]; }else{
NSLog(@"SAVE FAILED"); } sqlite3_finalize(statement); sqlite3_close(contactDB); } } @end