
การเขียนแอพพลิเคชันบน iPhone ด้วย Objective-C กับการเก็บข้อมูลลงไฟล์ข้อมูล Plist เช่นข้อมูลที่ต้องกรอกจากแอพฯ หรือข้อมูลที่ดาวน์โหลดมาเก็บไว้ในเครื่องก่อน
ก่อนจะเข้าสู่การพัฒนาแอพพลิเคชันบน iOS8 เราก็ยังคงมีบทความการพัฒนา Objective-C กับ iOS7 ประกอบกันไปซึ่งบทเรียนนี้มีคนถามหากันบ่อยมากคือการเก็บข้อมูลลงในไฟล์ Plist ของเครื่อง iPhone ของเราครับ
เราจำเป็นจะต้องรู้โครงสร้างระบบไฟล์ในแอพพลิเคชันของเราก่อนว่ามันถูกเรียกมาจากที่ไหน โดยเฉพาะตอนทดสอบนั้นจะต้องรู้ว่ามีไฟลของเราจะไปเก็บไว้ที่ Simulator ของ iPhone คือตำแหน่งอะไร ก่อนจะเริ่มโปรเจ็คนี้ให้เปิด Terminal ขึ้นมาก่อนครับ แล้วพิมพ์คำสั่งนี้ลงไปเพื่อ ให้อ่าน Folder ที่ถูก Hidden หรือถูกซ่อนไว้ก่อนได้
sudo chflags nohidden /Library/ ~/Library/
ต่อมาเปิด XCode ขึ้นมาครับ เลือก Single View Application เลยตั้งชื่อให้เรียบร้อย



เปิดไฟล์ ViewController.m ขึ้นมาแล้วใส่คำสั่งต่อไปนี้ ในเมธอด ViewDidLoad();
เราต้องหา Path ของเครื่อง iPhone ของเราก่อน ผ่านคำสั่ง NSSearchPathForDirectoriesDomains เพราะแอพพลิเคชันของเราจะเก็บข้อมูลไว้ใน Folder เป็นรหัสที่เราไม่สามารถจำได้บ่อยๆ นักครับ
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0];
ทีนี้เราจะได้ Paths เก็บไฟล์แล้ว เราจะเอานามสกุลต่อท้ายไปเลย คือ .plist เพราะว่า ชื่อที่ระบบจะเก็บคือ Documents ครับ
ข้อมูลที่เราจะเก็บลง Plist ก็คือข้อมูลประเภท Array ดังตัวอย่างนี้ครับ
NSArray *array = @[@"The Game Of Thrones Season 4", @"HBO Series"];
เก็บข้อมูลลงไฟล์ก็ใช้คำสั่งนี้
NSString *filePath = [documentsDirectory stringByAppendingString:@".plist"]; [array writeToFile:filePath atomically:YES];
ดังนั้นภาพรวมของ ViewController.m ก็จะประกอบไปด้วย Code ตามนี้ครับ
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; NSArray *array = @[@"The Game Of Thrones Season 4", @"HBO Series"]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSLog(@"Directory: %@", documentsDirectory); NSString *filePath = [documentsDirectory stringByAppendingString:@".plist"]; [array writeToFile:filePath atomically:YES]; NSLog(@"Store Data at: %@",filePath); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
ทดลอง Run ตัวแอพพลิเคชันของเราดู จะเห็นว่า NSLog ของเราจะบอก Paths และชื่อไฟล์เรียบร้อยให้ตามไปดูด้วย Finder ครับ

ใน Folder จะพบไฟล์ .plist ของเราให้ลองเปิดดู

จะพบว่าข้อมูล Array ของเราถูกเก็บในไฟล์ Documents.plist เรียบร้อยแล้วครับ

เป็นบทเรียนสั่นๆ ที่เกี่ยวกับการ เก็บข้อมูลโครงสร้าง Plist ไว้ในเครื่องของเราครับ ลองเอาไปลองทำกันดูนะครับ ตัวอย่างง่ายมากๆ Source Code ก็ไม่ต้องมีหรอกเนอะ…
One Comment