標籤:blog http io ar os for 檔案 資料 on
實際開發中,儲存資料主要是用SQLite。而在練習中,我們主要用如下三種儲存方式。
(1)利用plist儲存簡單地NSString、NSArray、NSDictionary等。
(2)利用preference儲存,和上面的類似,儲存的是簡單的資料,本質上還是一個plist檔案。
(3)利用NSCoding儲存物件這些複雜的資料,本質上是一個data檔案,需要被儲存的類遵守NSCoding協議並實現init和encode方法。
代碼如下:
——在ViewController.m中
- (void)viewDidLoad { //我們儲存的資料主要是存在Documents中,會被iTunes備份 //tmp中資料可能會被隨時清除 //Library中的Caches儲存的時緩衝,不會被清除,但也不會被iTunes備份 //Library中的Preference儲存的時喜好設定,會被iTunes備份 //1、儲存到plist檔案中 NSString *homePath=NSHomeDirectory(); NSString *docPath=[homePath stringByAppendingPathComponent:@"Documents"]; NSString *filePath=[docPath stringByAppendingPathComponent:@"data2plist.plist"]; NSArray *[email protected][@"aaa",@10,@"hello"]; [array writeToFile:filePath atomically:YES]; //1、讀取plist檔案 NSArray *arrayOut=[NSArray arrayWithContentsOfFile:filePath]; for (int i=0; i<arrayOut.count; i++) { NSLog(@"%@",arrayOut[i]); } //2、儲存到preference中,相比plist,就是少了路徑,因為這個路徑是紫銅自動判斷的 NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults]; [defaults setObject:@"hello" forKey:@"1"]; [defaults setBool:YES forKey:@"yue"]; [defaults setInteger:10 forKey:@"age"]; //立即同步(好習慣) [defaults synchronize]; //2、讀取資料 NSString *str1=[defaults objectForKey:@"1"]; BOOL bool1=[defaults boolForKey:@"yue"]; int integer1=[defaults integerForKey:@"age"]; NSLog(@"%@,%d,%i",str1,bool1,integer1); //以上需要注意的是,preference資料存放的地方和xcode5的模擬器不同 //3、用NSCoding儲存對象 WPPerson *p1=[[WPPerson alloc]init]; [email protected]"andy"; p1.age=30; NSString *filePath2=[docPath stringByAppendingPathComponent:@"data2data.data"]; [NSKeyedArchiver archiveRootObject:p1 toFile:filePath2]; //3、讀取資料 WPPerson *p2=[NSKeyedUnarchiver unarchiveObjectWithFile:filePath2]; NSLog(@"%@,%i",p2.name,p2.age); [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib.}
——為了第三個例子建立了一個WPPerson類,繼承自NSObject的簡單地類。
WPPerson.h中:
#import <Foundation/Foundation.h>@interface WPPerson : NSObject<NSCoding>@property(nonatomic,copy) NSString *name;@property(nonatomic,assign) int age;@end
WPPerson.m中:
#import "WPPerson.h"@implementation WPPerson-(void)encodeWithCoder:(NSCoder *)aCoder{ [aCoder encodeObject:_name forKey:@"name"]; [aCoder encodeInt:_age forKey:@"age"];}-(id)initWithCoder:(NSCoder *)aDecoder{ if (self=[super init]) { _name=[aDecoder decodeObjectForKey:@"name"]; _age=[aDecoder decodeIntForKey:@"age"]; } return self;}@end
【iOS開發-75】iOS資料存放區的三種簡單方式:plist、preference以及用NSCoding儲存物件