码迷,mamicode.com
首页 > 移动开发 > 详细

iOS -归档

时间:2015-08-19 22:42:48      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

Student.h

#import <Foundation/Foundation.h>

@interface Student : NSObject<NSCoding>
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) int ID;
@end

Student.m

#import "Student.h"

@implementation Student
//归档
- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:_name forKey:@"name"];
    [aCoder encodeInt:_ID forKey:@"ID"];
    
    
}

//解归档
- (id)initWithCoder:(NSCoder *)aDecoder
{
    _name = [aDecoder decodeObjectForKey:@"name"];
    _ID = [aDecoder decodeIntForKey:@"ID"];
    
    return self;
}
@end

main

#import <Foundation/Foundation.h>
#import "Student.h"
#define PATH @"/Users/aoyolo5/Desktop/keyedArchiver"
#define PATH2 @"/Users/aoyolo5/Desktop/StudenArchiver"
int main(int argc, const char * argv[]) {
    @autoreleasepool {
      //数据持久化:归档(可以存储自定义类的对象,还可以加密)
        NSArray *array = @[@"1",@"2",@"3"];

//        //归档(内容是加密过的)
        [NSKeyedArchiver archiveRootObject:array toFile:PATH];
//
//        //解归档
       NSArray *array2 = [NSKeyedUnarchiver unarchiveObjectWithFile:PATH];
//        NSLog(@"%@",array2);
        
        //NSMutableData 归档
        //1.创建NSKeyedArchiver对象
        NSMutableData *mData = [[NSMutableData alloc]initWithCapacity:10];
        NSKeyedArchiver *keyArchiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:mData];
        
        //2.重复归档
        [keyArchiver encodeObject:@"张峰的个人信息" forKey:@"10001"];
        [keyArchiver encodeObject:array forKey:@"array"];
        
        //3.结束归档
        [keyArchiver finishEncoding];
        
        //4.NSMutableData存入当文件
        [mData writeToFile:PATH atomically:YES];
        
        //NSMutableData 解归档
        //1.
        NSMutableData *mData2 = [[NSMutableData alloc]initWithContentsOfFile:PATH];
        //2.解归档对象
        NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:mData2];
        
        NSString *str = [unArchiver decodeObjectForKey:@"10001"];
        NSLog(@"%@",str);
        
        NSArray *array3 = [unArchiver decodeObjectForKey:@"array"];
        NSLog(@"%@",array3);
        
        //归档自定义对象
        //对象必须遵循NSCoding协议,并且要实现协议中的方法
        Student *stu = [[Student alloc]init];
        stu.name = @"胡命淘";
        stu.ID = 150401;
        [NSKeyedArchiver archiveRootObject:stu toFile:PATH2];
        Student *stu2 = [NSKeyedUnarchiver unarchiveObjectWithFile:PATH2];
        NSLog(@"%@ %d",stu2.name,stu2.ID);
            }
    return 0;
}

 

iOS -归档

标签:

原文地址:http://www.cnblogs.com/sunbinboke/p/4743276.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!