序列化与反序列化

下面介绍下Object C中通过NSKeyedArchiver序列化与反序列化:

序列化中将对象写到文件中,反序列化则从文件中读取数据并构造对象。NSKeyedArchiver需要实现NSCoding中的两个函数initWithcoder()和encodeWithCoder()。

代码如下

//
//  SoreCard.h
//  SerializationTest
//  序列化与反序列化
//  Created by Dwen on 12-11-22.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//
#import <Foundation/Foundation.h>

@interface SoreCard : NSObject<NSCoding>

@property (strong,nonatomic) NSString *bestTime;
@property (strong,nonatomic) NSMutableArray *allTime;

- (void) create;
- (void) print;
@end
#import "SoreCard.h"
@implementation SoreCard
@synthesize bestTime;
@synthesize allTime;

- (id)initWithCoder:(NSCoder *)aDecoder{
    if (self == [super init]) {
        bestTime = [aDecoder decodeObjectForKey:@"bestTime"];
        allTime = [aDecoder decodeObjectForKey:@"allTime"];
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeObject:bestTime forKey:@"bestTime"];
    [aCoder encodeObject:allTime forKey:@"allTime"];
}

- (void) create{
    bestTime = @"序列化与反序列化测试";
    allTime = [[NSMutableArray alloc] initWithObjects:@"中国",@"美国",@"德国", nil];
}

- (void) print{
    NSLog(@"BestTime name : %@",bestTime);
    for(NSString *str in allTime){
        NSLog(@"str : %@",str);
    }
}

@end
//
//  main.m
//  SerializationTest
//
//  Created by  on 12-11-22.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import <UIKit/UIKit.h>

#import "AppDelegate.h"
#import "SoreCard.h"

#define ARCHIVE 0
#define UNARCHIVE 1

int main(int argc, char *argv[])
{
    @autoreleasepool {
        //路径
        NSString *homePath = [[NSBundle mainBundle] executablePath];
        NSArray *strings = [homePath componentsSeparatedByString: @"/"];
        NSString *executableName  = [strings objectAtIndex:[strings count]-1];	
        NSString *baseDirectory = [homePath substringToIndex:
                                   [homePath length]-[executableName length]-1];	
        
//        NSString *fileName = [NSString stringWithFormat:@"%@/roster.archive",baseDirectory];
        NSString *fileName = [NSString stringWithFormat:@"%@/test.txt",baseDirectory];
        NSLog(@"filePath: %@",fileName);
        
#if ARCHIVE
        SoreCard *card = [[SoreCard alloc] init];
        [card create];
        //将类写入文件
        [NSKeyedArchiver archiveRootObject:card toFile:fileName];
#endif
    
#if UNARCHIVE
        //将类从文件中读出
        SoreCard *soreCard = [NSKeyedUnarchiver unarchiveObjectWithFile:fileName];
        [soreCard print];
#endif
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值