關於沙箱的讀寫檔案的幾種方式,沙箱讀寫幾種
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// h擷取應用沙箱
NSString *homaPath = NSHomeDirectory();
NSLog(@"%@",homaPath);
}
/**
* 下面的是用 plist 方式 儲存 資料
*/
-(void)savePlist{
NSString *homePath = NSHomeDirectory();
NSString *filePath = [homePath stringByAppendingPathComponent:@"Docments"];
// 指定檔案格式
NSString *format = [filePath stringByAppendingPathComponent:@"xx.plist"];
NSArray *data = @[@"房蘭峰1",@"房蘭峰2"];
[data writeToFile:format atomically:YES];
// 下面的是第二種方式---》系統提供的
NSString *dataPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *filePathNssear = [dataPath stringByAppendingPathComponent:@"xx.plist"];
}
/**
* 下面的是 plist 讀取 資料
*/
-(void)readPlist{
// 指定是哪個檔案
NSString *homePath = NSHomeDirectory();
NSString *filePath = [homePath stringByAppendingPathComponent:@"Documents"];
// 擷取資料
NSArray *data = [NSArray arrayWithContentsOfFile:filePath];
}
//preference 方式 ---> 喜好設定
-(void)preferenceSave{
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
[ud setObject:@"value11" forKey:@"key1"];
[ud setObject:@"value2" forKey:@"key2"];
// 同步,一定要寫這一步
[ud synchronize];
}
/**
* 下面是 preference 的讀取方式
*/
-(void)preferenceRead{
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
NSLog(@"%@",[ud objectForKey:@"key1"]);
}
/**
* 資料的儲存與讀取 ==== >>>>>> 歸檔與解檔
*/
-(void)keyedArchiverWrite{
NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *filePath = [docPath stringByAppendingPathComponent:@"xx.data"];
Teacher *teacher = [[Teacher alloc] init];
teacher.name = @"垃圾";
teacher.age = 10;
// 歸檔
[NSKeyedArchiver archiveRootObject:teacher toFile:filePath];
}
-(void)keyedUnarchiverRead{
NSString *filePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *documentType = [filePath stringByAppendingPathComponent:@"xx.data"];
Teacher *taecher = [NSKeyedUnarchiver unarchiveObjectWithFile:documentType];
}
@end