![](https://www.daydev.com/wp-content/uploads/2014/09/Screen-Shot-2557-09-14-at-7.13.05-PM.png)
บทเรียนก่อนหน้านี้ที่เกี่ยวข้องคือ เขียนแอพ iPhone ภาษา Objective-C เขียนไฟล์ Plist ครับ บทเรียนที่แล้วเราจะมีไฟล์ Plist ที่ถูกเขียนขึ้นมาเก็บไว้ใน Simulator Folder เสร็จสรรพ บทเรียนนี้คือการอ่านค่าเจ้าไฟล์ Plist ที่เขียนไว้เมื่อครู่ครับ
![สร้างมาใหม่เลย](https://www.daydev.com/wp-content/uploads/2014/09/Screen-Shot-2557-09-14-at-7.09.51-PM.png)
สร้าง Single View Application ขึ้นมาใหม่เลย สำหรับอ่านไฟล์ Plist นี้ แก้ไข ViewController.m ตามนี้ครับ
![เจอแล้ว!!](https://www.daydev.com/wp-content/uploads/2014/09/Screen-Shot-2557-09-14-at-7.15.04-PM.png)
เริ่มต้น เราจะทำการตรวจสอบว่า เราพบไฟล์ดังกล่าวนี้อยู่หรือเปล่าเราจะใช้คำสั่งในการตรวจสอบต่อไปนี้
NSFileManager *fileManager = [NSFileManager defaultManager]; if([fileManager fileExistsAtPath:filePath]){ NSLog(@"Exist"); }else{ NSLog(@"Not Exist"); }
ถ้าพบไฟล์ ก็ให้บอกเราว่า “Exist” ถ้าไม่พบก็จะเตือนบอกเราว่า “Not Exist” ครับ
ไฟล์ ViewController.m จะมี code ทั้งหมดเป็นแบบนี้
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *filePath = [documentsDirectory stringByAppendingString:@".plist"]; NSLog(@"Directory: %@", filePath); NSFileManager *fileManager = [NSFileManager defaultManager]; if([fileManager fileExistsAtPath:filePath]){ NSLog(@"Exist"); }else{ NSLog(@"Not Exist"); } } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
ทำการ Run ตัวแอพพลิเคชันของเราเพื่อตรวจสอบหน่อยว่าเจอหรือไม่?
![เจอแล้ว!!](https://www.daydev.com/wp-content/uploads/2014/09/Screen-Shot-2557-09-14-at-7.15.04-PM.png)
ต่อมาให้เราทำการอ่านค่าจากไฟล์ขึ้นมาครับ โดยคำสั่งนี้
NSArray *array=[[NSArray alloc] initWithContentsOfFile:filePath]; for (int i=0; i<2; i++){ NSLog(@"%@",array[i]); }
นำไปวางที่ตำแหน่งดังตัวอย่างครับ
if([fileManager fileExistsAtPath:filePath]){ NSLog(@"Exist"); NSArray *array=[[NSArray alloc] initWithContentsOfFile:filePath]; for (int i=0; i<2; i++){ NSLog(@"%@",array[i]); } }else{ NSLog(@"Not Exist"); }
ลอง Run ตัวแอพพลิเคชันของเราใหม่อีกครั้งแล้วดูที่ console ใหม่ครับว่า ค่ามาหรือเปล่า
![อ่าน Plist ไฟล์](https://www.daydev.com/wp-content/uploads/2014/09/Screen-Shot-2557-09-14-at-7.27.54-PM.png)
หวังว่าคงไม่อยากเกินไป Source code ก็ไม่ต้องมีหรอกครับ ง่ายแค่นี้เอง ถ้า Copy Code ไปวางแล้วยัง Error ก็พิจารณาตัวเองใหม่นะครับ 😀