標籤: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自訂類歸檔使用詳解