您的位置:首页 > 其它

归档 解档

2015-11-28 20:18 211 查看
//系统类型的对象归档(NSString/NSArray/NSDictionary)

//1、设置归档路径,该路径需要详细到文件(不能是文件夹)

//2、得到要归档的对象

//3、通过NSKeyedArchiver调用archiveRootObject方法,进行归档

//4、解档 通过NSKeyedUnarchiver调用unarchiveObjectWithFile进行解档,注意,该方法返回值类型为id

//字符串的归档 解档

NSString *path = NSHomeDirectory();

NSString *documents = [path stringByAppendingPathComponent:@"Documents"];

NSString *strpath = [documents stringByAppendingPathComponent:@"string.txt"];

NSString *newstr = @"新闻联播";

[NSKeyedArchiver archiveRootObject:newstr toFile:strpath];

NSLog(@"%@",strpath);

NSString *str = [NSKeyedUnarchiverunarchiveObjectWithFile:strpath];

NSLog(@"---%@",str);

//数组的归档 解档

NSString *arrpath = [documents stringByAppendingPathComponent:@"arr.txt"];

NSArray *arr = @[@"1",@"2",@"3"];

[NSKeyedArchiverarchiveRootObject:arr toFile:arrpath];

NSArray *arr1 = [NSKeyedUnarchiver unarchiveObjectWithFile:arrpath];

NSLog(@"%@",arr1);

///////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////

#import "ViewController.h"

#import "Student.h"

@interfaceViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {

[superviewDidLoad];

NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/student.txt"];

NSLog(@"%@",path);

Student *stu= [[Student alloc]init];

stu.name = @"张三";

[NSKeyedArchiverarchiveRootObject:stu toFile:path];

Student *s1 = [NSKeyedUnarchiverunarchiveObjectWithFile:path];

NSLog(@"%@",s1.name);

}

#import <Foundation/Foundation.h>

//如果需要对自定义类进行归档,则该类需要遵循NSCoding协议,并且实现其协议方法

@interface Student : NSObject<NSCoding>

@property (nonatomic,copy) NSString *name;

@end

#import "Student.h"

@implementation Student

//实现encodeWithCoder协议方法,当系统对自定义类的对象进行归档时,会调用此方法,归档其属性

-(void) encodeWithCoder:(NSCoder *)aCoder

{

[aCoder encodeObject:self.name forKey:@"name"];

}

//实现initWithCoder方法,当系统对自定义类的对象进行解档时,会调用此方法,可以看成是一个初始化的过程,返回一个对象,并且对其属性进行解档

-(id) initWithCoder:(NSCoder *) aDecoder

{

self = [super init];

if (self) {

self.name = [aDecoder decodeObjectForKey:@"name"];

}

returnself;

}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: