您的位置:首页 > 其它

自定义类写入文件

2015-06-10 09:29 274 查看
 //对自定义类归档

Person.h  遵守<NSCoding>协议

#import <Foundation/Foundation.h>

@class Book;

@interface Person : NSObject<NSCoding>

@property(copy,nonatomic)NSString *name;

@property(copy,nonatomic)NSString *sex;

@property(strong,nonatomic)Book *book;

@end

Person.m

#import "Person.h"

@implementation Person

-(void)encodeWithCoder:(NSCoder *)aCoder

{

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

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

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

}

-(id)initWithCoder:(NSCoder *)aDecoder

{

    self = [super init];

    if (self) {

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

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

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

    }

    return self;

}

@end

----------------------写入文件-----------------

创建对象

    Book *book1 = [[Book alloc] init];

    book1.name = @"西游记";

    //写入自定义类

    Person *p1 = [[Person alloc] init];

    Person *p2 = [[Person alloc] init];

    Person *p3 = [[Person alloc] init];

    p1.name = @"wyj1";

    p1.sex = @"男1";

    p1.book = book1;

用archive归档

    NSMutableData *data = [NSMutableData data];

    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];

    [archiver encodeObject:p1 forKey:@"person"];

    [archiver finishEncoding];

获取文件路径

NSString *doucment = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];

    doucment = [doucment stringByAppendingString:@"/save"];

将data写入文件

[data writeToFile:doucment atomically:YES];

--------------自定义类对象从文件读取--------------

1.先获取路径

NSString *doucment = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];

    doucment = [doucment stringByAppendingString:@"/save"];

NSData *data = [NSData dataWithContentsOfFile:doucment];

2.将NSData通过反归档,转化为Personz对象

NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];

3.通过反归档得到复杂对象

Person *p = [unarchiver decodeObjectForKey:@"person"];

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