#import "ViewController.h" #import "dog.h" @interface ViewController () @end @implementation ViewController //存數據 - (IBAction)writeDataAction:(UIButto ...
#import "ViewController.h"
#import "dog.h"
@interface ViewController ()
@end
@implementation ViewController
//存數據
- (IBAction)writeDataAction:(UIButton *)sender {
//1.獲取存儲的路徑
NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *filePath = [documents stringByAppendingPathComponent:@"data.plist"];
//2.創建對象
dog *superDog = [[dog alloc]init];
superDog.name = @"旺財";
superDog.age = 18;
superDog.isTrue = YES;
//3.歸檔 NSKeyedArchive
//如果使用歸檔 ,所歸檔的對象 必須遵守NSCoding 協議, 編碼協議
[NSKeyedArchiver archiveRootObject:superDog toFile:filePath];
NSLog(@"%@",filePath);
}
//讀取數據
- (IBAction)readDataAction:(UIButton *)sender {
//1.獲取存儲的路徑
NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *filePath = [documents stringByAppendingPathComponent:@"data.plist"];
//取出存儲的對象
dog *superDog = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
NSLog(@"%@今年%@歲了??? === %@",superDog.name,@(superDog.age),@(superDog.isTrue));
}