• No results found

โปรแกรมบ นท ก ช อ และ อ เมล โดยจ ดเก บข อม ลลงไปท SQLite

N/A
N/A
Protected

Academic year: 2021

Share "โปรแกรมบ นท ก ช อ และ อ เมล โดยจ ดเก บข อม ลลงไปท SQLite"

Copied!
31
0
0

Loading.... (view fulltext now)

Full text

(1)
(2)

Application => Single View Application => Next

Product Name = ContactLite, Devices = iPhone, Use Storyboards, Use Automatic Reference Counting

(3)
(4)

เลือกไปที่ TARGETS => Build Pharses => “+”

(5)
(6)
(7)

เปิดไฟล์ 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

(8)

วาง Navigation Bar, Table View, Table View Cell และ Bar Button Item ตาม ลําดับลงบนรูปด้านล่างนี้

(9)
(10)

คลิกไปที่ปุ่มตามรูปด้านล่าง “Item” แล้วไปที่ไอคอน Attribute เปลี่ยนค่า Identifier = Add

(11)

เลือกไปคลิกที่ Table View Cell ตามรูปด้านล่างนี้ แล้วไปเปลี่ยนค่าของ Style = Subtitle, Identifier = Cell

(12)

เปิดไฟล์ 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

(13)

เปิดไฟล์ 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"); }

} }}

(14)

เปิดไฟล์ 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);

} }

(15)

เปิดไฟล์ 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; }

(16)

เปิดไฟล์ 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;

(17)

เปิดไฟล์ 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]; }

(18)

เปิดไฟล์ 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

(19)
(20)

ตั้งค่า 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;

(21)

เปิดไฟล์ 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. }

(22)

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

(23)

ทําการเชื่อมโยงหน้าจอดังรูปด้านล่างเข้าไปเชื่อมกับ navItem

(24)

ทําการคลิกขวาที่ Table View แล้วทําการเชื่อม dataSource และ

delegate ไปยังไอคอนสีเหลืองด้านล่างดังภาพ

(25)
(26)

คลิกขวาที่ไอคอนสีเหลืองดังรูปด้านล่าง แล้วทําการเชื่อ modal ไป

ยังไอคอน “+”

(27)

คลิกขวาที่ไอคอนสีเหลืองดังรูปด้านล่าง แล้วไปเลือกไอคอนที่ 3

ตามรูปแล้วทําการเปลี่ยน Class = SaveViewController

(28)

วาง Label 2 อันตั้งค่า Text = NAME, EMAIL ตามรูป

วาง Text Field 2 อัน และ ปุ่มตั้งค่า Text = SAVE

(29)
(30)
(31)

References

Related documents

Colonial partnered with Farm Credit of the Virginias, AgChoice Farm Credit, and MidAtlantic Farm Credit to cater a lunch for House and Senate representatives to provide

Using bank level data for Argentina, Chile, Colombia, and Peru during the mid-1990s, this study empirically investigates whether bank origin affects the share and growth rate of

Business intelligence can be moved to cloud using Platform as services. It is a cloud-based relational database service built on database technologies. It provides a highly

5.3 Transport chain trends: efficiency, additional services 5.3.1 Increasing use of logistics service providers.. In the global economy, logistics service providers

Note: Incidences were estimated using two data sources – the mandatory notification system and the Associations of Statutory Health Insurance Physicians (ASHIP) – and expressed as

Namun, dalam praktik transaksi jual beli barter minuman kopi di Kedai Sampah di Gresik ini, pihak pemilik kedai/pengelola tidak melakukan standarisasi atau prediksi harga