IOS- NSCoding協議,NSKeyedArchiver自訂類歸檔使用詳解

來源:互聯網
上載者:User

標籤:nscoding協議   ios歸檔   nskeyedarchiver   

使用NSCoding協議可以實現歸檔自訂的類,NSKeyedArchiver可以歸檔我們自訂的類;要實現自訂類的歸檔,需要實現

encodeWithCoder(編碼)和initWithCoder(解碼)

我建立一個自訂的Student類,遵循NSCoding協議,實現這兩個方法:

////  Student.h//  UserList////  Created by http://blog.csdn.net/yangbingbinga on 14/11/14.//  Copyright (c) 2014年 http://blog.csdn.net/yangbingbinga. All rights reserved.//#import <Foundation/Foundation.h>@interface Student : NSObject<NSCoding>@property(nonatomic,strong)NSString * name;@property(nonatomic,strong)NSString * age;@end
.m檔案

////  Student.m//  UserList////  Created by yb on 14/11/14.//  Copyright (c) 2014年 http://blog.csdn.net/yangbingbinga. All rights reserved.//#import "Student.h"@implementation Student- (void)encodeWithCoder:(NSCoder *)aCoder{    NSLog(@"%s",__FUNCTION__);    [aCoder encodeObject:self.name forKey:@"name"];    [aCoder encodeObject:self.age forKey:@"age"];    }- (id)initWithCoder:(NSCoder *)aDecoder{    NSLog(@"%s",__FUNCTION__);    self.name = [aDecoder decodeObjectForKey:@"name"];    self.age = [aDecoder decodeObjectForKey:@"age"];        return self;}@end

我們可以直接在appDelegate中測試一下,如何 歸檔 和 讀取 歸檔的資料:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{    Student * stu = [[Student alloc]init];    stu.name = @"123";    stu.age = @"3";    NSData * stuD = [NSKeyedArchiver archivedDataWithRootObject:stu];//歸檔,調用encodeWithCoder方法                Student * stu1 = [NSKeyedUnarchiver unarchiveObjectWithData:stuD];//讀取歸檔資料,調用initWithCoder    NSLog(@"stu1.name = %@",stu1.name);    return YES;}
原文地址:http://blog.csdn.net/yangbingbinga


IOS- NSCoding協議,NSKeyedArchiver自訂類歸檔使用詳解

聯繫我們

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