iOS UI16_資料持久化

來源:互聯網
上載者:User

標籤:any   views   defaults   elf   方便   dcl   它的   使用   另一個   

////  Student.h//  UI16_資料持久化////  Created by dllo on 15/8/19.//  Copyright (c) 2015年 zhozhicheng. All rights reserved.//#import <Foundation/Foundation.h>#pragma mark 假設想實現歸檔和反歸檔的操作須要先簽訂一個協議NSCoding@interface Student : NSObject<NSCoding>@property(nonatomic,copy)NSString *name;@property(nonatomic,copy)NSString *sex;@property(nonatomic,assign)NSInteger age;@property(nonatomic,copy)NSString *hobby;//針對這四條屬性,寫一個自己定義初始化方法和便利構造器-(instancetype)initWithName:(NSString *)name                sex:(NSString *)sex                age:(NSInteger)age              hobby:(NSString *)hobby;+(instancetype)studentWithName:(NSString *)name                 sex:(NSString *)sex                 age:(NSInteger)age               hobby:(NSString *)hobby;@end
////  Student.m//  UI16_資料持久化////  Created by dllo on 15/8/19.//  Copyright (c) 2015年 zhozhicheng. All rights reserved.//#import "Student.h"@implementation Student-(instancetype)initWithName:(NSString *)name                sex:(NSString *)sex                age:(NSInteger)age              hobby:(NSString *)hobby{    self=[super init];    if (self) {        _age =age;        _name =name;        _hobby =hobby;        _sex =sex;    }    return self;}+(instancetype)studentWithName:(NSString *)name                           sex:(NSString *)sex                           age:(NSInteger)age                         hobby:(NSString *)hobby{    Student *stu = [[Student alloc] initWithName:name sex:sex age:age hobby:hobby];    return stu;}#pragma mark 簽訂完NSCoding協議之後,須要實現兩個協議方法,一個是歸檔的時候使用的,一個是反歸檔的時候使用的- (void)encodeWithCoder:(NSCoder *)aCoder{    [aCoder encodeObject:self.name forKey:@"姓名"];    [aCoder encodeInteger:self.age forKey:@"年齡"];    [aCoder encodeObject:self.hobby forKey:@"愛好"];    [aCoder encodeObject:self.sex forKey:@"性別"];    //使用encode方法要和資料的類型相互匹配}- (id)initWithCoder:(NSCoder *)aDecoder{    self = [super init];    if (self) {        //把資料依據之前的key再反編譯回來        self.name = [aDecoder decodeObjectForKey:@"姓名"];        self.age = [aDecoder decodeIntegerForKey:@"年齡"];        self.hobby = [aDecoder decodeObjectForKey:@"愛好"];        self.sex = [aDecoder decodeObjectForKey:@"性別"];    }    return self;}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end
////  ViewController.m//  UI16_資料持久化////  Created by dllo on 15/8/19.//  Copyright (c) 2015年 zhozhicheng. All rights reserved.//#import "ViewController.h"#import "Student.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.    //蘋果手機為了保證自己資料上的絕對安全,設計了沙箱檔案,每個應用程式上都配備了自己的沙箱檔案,每一次執行,目錄的名字就會變成一個沒有不論什麼規律的字串    //第一個參數:當前要前往那一個目錄,前往documents檔案用NSDocuemtDirectory,64行那個,還能夠前往caches目錄,相應68行    //第二個參數:訪問的目錄類型,指定訪問是使用者目錄    //第三個參數:絕對路徑(YES),相對路徑(NO)    //絕對路徑是給系統使用的,系統能夠依據當前的路徑找到目錄,我們在操作目錄時是絕對路徑    //相對路徑僅僅會把要前往的目錄顯示,其它部分都是~,告訴程式猿要去哪個目錄//    NSArray *sandbox =NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);//    NSLog(@"%@",sandbox[0]);    //沙箱裡一共同擁有三個檔案    //1.是Documents檔案:主要用來儲存使用者的想要儲存的一些資訊,比方收藏的資訊或者自己設定的一些內容,所以我們做收藏功能就是前往這個目錄裡寫檔案    //2.Library目錄裡是方便程式開發人員的,主要操作它裡面的兩個目錄,caches和Preferences    //caches:用來儲存快取檔案,SDWebImage會把圖片加到快取檔案裡,所以清除緩衝功能就是把這個目錄刪除    //Preferences:一般來儲存程式猿設定的資訊,比方NSUserDefults就會把資料儲存在這個目錄裡    //3.tmp檔案:一般存放暫時內容    //之前在沙箱裡另一個.app檔案,在新的版本號碼裡已經被移走了    //把簡單對象寫入到本地,簡單對象指的是NSString,NSArray//    //1.先通過數組擷取沙箱路徑//    NSArray *sandbox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);//    //從數組裡擷取沙箱路徑//    NSString *sandBoxPath =sandbox[0];//    //要給寫入的檔案拼接一個路徑,拼接方式有兩種////    NSString *documentPath = [sandBoxPath stringByAppendingString:@"/顧宇.txt"];//    //    NSString *documentPath = [sandBoxPath stringByAppendingPathComponent:@"顧宇.xml"];//    NSLog(@"%@",documentPath);//    NSString *str = @"書山有路勤為徑,學海無涯苦作舟";//    //把字串寫入到本地//    //第一個參數:檔案要儲存的路徑//    //第二個參數:對檔案進行保護YES//    //第三個參數:編碼//    //第四個參數,錯誤資訊//    [str writeToFile:documentPath atomically:YES encoding:NSUTF8StringEncoding error:nil];//    //假設路徑下有相應的檔案,則會把原來檔案覆蓋,假設沒有則建立一個新檔案//    //把沙箱檔案讀出來//    NSString *temoStr = [NSString stringWithContentsOfFile:documentPath encoding:NSUTF8StringEncoding error:nil];//    NSLog(@"%@",temoStr);//    //把數組寫入到本地//    NSArray *arr [email protected][@"1",@"2",@"3",@"4",@"5",@"6"];//    //通過數組擷取沙箱地址//    NSArray *sandbox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);//    //用字串儲存沙箱路徑//    NSString *sandboxPath = sandbox[0];//    //給要寫入的檔案拼接路徑//    NSString *documentPath = [sandboxPath stringByAppendingPathComponent:@"哈哈.plist"];//    //把數組寫入到本地//    [arr writeToFile:documentPath atomically:YES];//    NSLog(@"%@",documentPath);//    //    //把數組讀出來//    NSArray *temp = [NSArray arrayWithContentsOfFile:documentPath];//    NSLog(@"%@",temp);//    //把字典寫入到本地//    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"2", nil];//    NSArray *sandbox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);//    NSString *sandboxPath = sandbox[0];//    NSString *documentPath = [sandboxPath stringByAppendingPathComponent:@"嘿嘿"];//    [dic writeToFile:documentPath atomically:YES];//    NSLog(@"%@",documentPath);//    //    NSDictionary *temp = [NSDictionary dictionaryWithContentsOfFile:documentPath];//    NSLog(@"%@",temp);    //複雜物件寫入到本地,主要指我們自己建立的對象寫入到本地,也叫歸檔和犯反歸檔操作    //建立對象呢//    Student *stu1 = [Student studentWithName:@"張三" sex:@"男" age:14 hobby:@"玩"];//    //1.通過數組擷取沙箱路徑//    NSArray *sandbox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);//    //2.用字串截取沙箱路徑//    NSString *sandBoxPath = sandbox[0];//    //3.拼接目錄路徑,這個目錄擴充名是隨意的//    NSString *decomentPath = [sandBoxPath stringByAppendingPathComponent:@"學生.avi"];//    //對對象進行歸檔操作//    //第一個參數:要實施歸檔的對象//    //第二個參數:路徑//    [NSKeyedArchiver archiveRootObject:stu1 toFile:decomentPath];//    NSLog(@"%@",decomentPath);//    //    //反歸檔//    Student *newStu = [NSKeyedUnarchiver unarchiveObjectWithFile:decomentPath];//    NSLog(@"%@",newStu.name);//    //建立三個學生//    Student *stu1 = [Student studentWithName:@"張三" sex:@"男" age:14 hobby:@"玩"];//    Student *stu2 = [Student studentWithName:@"李四" sex:@"女" age:15 hobby:@"睡覺"];//    Student *stu3 = [Student studentWithName:@"神六" sex:@"男" age:16 hobby:@"唱歌"];//    NSArray *array = @[stu1,stu2,stu3];//    //    NSArray *sandbox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 1, YES);//    NSString *sandboxPath = sandbox[0];//    //拼接檔案路徑//    NSString *documentPath = [sandboxPath stringByAppendingPathComponent:@"曹軍.plist"];//    //歸檔操作//    [NSKeyedArchiver archiveRootObject:array toFile:documentPath];//    NSLog(@"%@",documentPath);//    //    //反歸檔,遍曆學生姓名//    NSArray *arr = [NSKeyedUnarchiver unarchiveObjectWithFile:documentPath];//    for (Student *temp in arr) {//        NSLog(@"%@",temp.name);//    }#warning 總結:資料持久化的步驟    //1.指定前往那一個目錄    //2.用字串接收路徑    //3.拼接檔案路徑    //4.寫入本地或歸檔操作    //注;假設是複雜物件歸檔,要簽訂NSCoding協議,而且實現兩個協議方法,放在數組裡的複雜物件歸檔也要簽協議//    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];//    [defaults setObject:@"123456" forKey:@"password"];//    NSArray *sandBox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 1, YES);//    NSLog(@"%@",sandBox[0]);//    NSLog(@"%@",[defaults objectForKey:@"password"]);    //NSUserDefaults一般存放的是小的資料,比方字串等,它的使用方法和字典相似    //通過檔案管理者對目錄進行操作    NSArray *sandBox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 1, YES);    NSString *sandBoxPath =sandBox[0];    //建立一個檔案管理者    NSFileManager *manager = [NSFileManager defaultManager];    //給要建立的目錄拼接一個路徑    NSString *filePath = [sandBoxPath stringByAppendingPathComponent:@"guyu"];    //目錄的名不須要副檔名    //通過manager進行目錄的建立    [manager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];    NSLog(@"%@",filePath);    //向目錄裡寫入一個字串    NSString *documentPath = [filePath stringByAppendingPathComponent:@"字串.txt"];    NSString *str = @"我是字串";    [str writeToFile:documentPath atomically:YES encoding:NSUTF8StringEncoding error:nil];    //移除目錄//    [manager removeItemAtPath:filePath error:nil];//    //清除緩衝    NSArray *cache = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, 1, YES);    NSString *cachePath =cache[0];    [manager removeItemAtPath:cachePath error:nil];}@end

iOS UI16_資料持久化

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.