【iOS開發-儲存】使用NSCoding歸檔和反歸檔

來源:互聯網
上載者:User

標籤:ios   歸檔   

iOS開發中要想儲存物件可以使用NSCoding,要想儲存的對象必須實驗NSCoding協議

比如我們要儲存一個Student對象,那麼Student類必須遵循NSCoding協議,然後實現NSCoding中得兩個方法。

@interface Student : NSObject  <NSCoding>

然後再.m檔案中實現encodeWithCoder:(存)和initWithCoder:(讀)方法,這樣就告訴了程式這個對象應該怎麼存,要存那些屬性,以及需要怎麼讀!

/** *  將某個對象寫入檔案時會調用 *  在這個方法中說清楚哪些屬性需要儲存 */- (void)encodeWithCoder:(NSCoder *)encoder{    [encoder encodeObject:self.no forKey:@"no"];    [encoder encodeInt:self.age forKey:@"age"];    [encoder encodeDouble:self.height forKey:@"height"];}
/** *  從檔案中解析對象時會調用 *  在這個方法中說清楚哪些屬性需要儲存 */- (id)initWithCoder:(NSCoder *)decoder{    if (self = [super init]) {        // 讀取檔案的內容        self.no = [decoder decodeObjectForKey:@"no"];        self.age = [decoder decodeIntForKey:@"age"];        self.height = [decoder decodeDoubleForKey:@"height"];    }    return self;}

控制器中得讀寫方法。

- (IBAction)save {    // 1.新的模型對象    Student *stu = [[Student alloc] init];    stu.no = @"42343254";    stu.age = 20;    stu.height = 1.55;    // 2.歸檔模型對象    // 2.1.獲得Documents的全路徑    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];    // 2.2.獲得檔案的全路徑    NSString *path = [doc stringByAppendingPathComponent:@"stu.data"];    // 2.3.將對象歸檔    [NSKeyedArchiver archiveRootObject:stu toFile:path];}

反歸檔(讀取)

- (IBAction)read {    // 1.獲得Documents的全路徑    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];    // 2.獲得檔案的全路徑    NSString *path = [doc stringByAppendingPathComponent:@"stu.data"];    // 3.從檔案中讀取MJStudent對象    Student *stu = [NSKeyedUnarchiver unarchiveObjectWithFile:path];}

【iOS開發-儲存】使用NSCoding歸檔和反歸檔

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.