iOS 数据存储 - 归档和解归档

时间:2024-01-17 19:33:02

这里的归档主要是用于自定义类的归档和解档。我们这里使用NSKeyedArchiver和NSKeyedUnarchiver来归档和解档。

注意:自己定义的类需要实现<NSCoding>,如:@interface User : NSObject <NSCoding>,并实现Coding中相应的方法。

/*************************************User.h*************************************/

//

// User.h

// customContentArchiveDemo

//

// Created by Warrior on 14-1-7.

// Copyright (c) 2014年 Warrior. All rights reserved.

//

#import <Foundation/Foundation.h>

@interface User : NSObject <NSCoding>

@property(nonatomic,copy)NSString *name;

@property(nonatomic,copy)NSString *email;

@property(nonatomic,copy)NSString *passWord;

@property(nonatomic,assign)int age;

@end

/*************************************User.m*************************************/

//

// User.m

// customContentArchiveDemo

//

// Created by Warrior on 14-1-7.

// Copyright (c) 2014年 Warrior. All rights reserved.

//

#import “User.h”

#define NAME @“name”

#define EMAIL @“email”

#define PASSWORD @“passWord”

#define AGE @“age”

@implementation User

@synthesize name;

@synthesize email;

@synthesize passWord;

@synthesize age;

//对属性解码,解档的时候调用

- (id)initWithCoder:(NSCoder *)aDecoder

{

if(self = [super init])

{

//注意这里要添加self

name = [aDecoder decodeObjectForKey:NAME];

email = [aDecoder decodeObjectForKey:EMAIL];

passWord = [aDecoder decodeObjectForKey:PASSWORD];

age = [aDecoder decodeIntForKey:AGE];

}

return self;

}

//对属性编码,归档的时候调用

- (void)encodeWithCoder:(NSCoder *)aCoder

{

[aCoder encodeObject:name forKey:NAME];

[aCoder encodeObject:email forKey:EMAIL];

[aCoder encodeObject:passWord forKey:PASSWORD];

[aCoder encodeInt:age forKey:AGE];

}

@end

使用归档和解档的方法来实现保存数据。

/*************************************main.m*************************************/

//

// main.m

// customContentArchiveDemo

//

// Created by Warrior on 14-1-7.

// Copyright (c) 2014年 Warrior. All rights reserved.

//

#import <Foundation/Foundation.h>

#import “User.h”

int main(int argc, const char * argv[])

{

@autoreleasepool {

//归档

NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@”user.archive”];

NSFileManager *fileManger = [NSFileManager defaultManager];

if(![fileManger fileExistsAtPath:filePath])

[fileManger createFileAtPath:filePath contents:nil attributes:nil];

User *user = [[User alloc] init];

user.name = @”Warrior Sun”;

user.email = @”suenihy@hotmail.com”;

user.passWord = @”123456”;

user.;

if([NSKeyedArchiver archiveRootObject:user toFile:filePath])

{

NSLog(@”归档成功”);

}

//解档

User *unUser = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];

NSLog(@”User name:%@”, unUser.name);

}

;

}

—————————————————————————————————————————————————————————————

要保存基本数据类型,如int,NSString等,可以将user的变量修改为相应的基本类型变量。