IOS本地保存(归档)


归档(存为二进制文件)


NSString *str = @“my name is Lemon";
NSString *path = @“/Users/student/Desktop/string.data";


//字符串的归档和解档
1.归档
[NSKeyedArchiver archiveRootObject:str toFile:path];

2.解档
NSString *newStr = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        NSLog(@"newStr = %@“,newStr);


//数组的归档和解档

        NSArray *arr = [[NSArray alloc] initWithObjects:@"柠檬",@"芒果",@"山楂", nil];
        [NSKeyedArchiver archiveRootObject:arr toFile:path];
        NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        for (id obj in array)
        {
            NSLog(@"%@",obj);
        }



//如果想要对这个类的对象进行对象和归档
//1.遵守归档的协议 NSCoding
//2.实现协议中需要实现的两个方法:归档和解档
@interface Person : NSObject<NSCoding>
{
    NSString* _name;
    int _age;
}

@property NSString *name;
@property int age;

@end

#import "Dog.h"

@implementation Dog
//编码的方法,归档的时候,系统会使用这个方法
- (void)encodeWithCoder:(NSCoder *)aCoder
{
   //
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeObject:[NSNumber numberWithInt:self.age] forKey:@"age"];
}
//解码的方法,解档的时候系统会使用这个方法
- (id)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super init])
    {
        //为当前对象的属性赋值
        self.name = [aDecoder decodeObjectForKey:@"name"];
        self.age = [[aDecoder decodeObjectForKey:@"age"] intValue];
    }
    return self;
}

@end


#import "Dog.h"

@interface WolfDog : Dog<NSCoding>
{
    //属性
    int _attackPower;
}

@property int attackPower;

@end
@implementation WolfDog

//为了能归档和解档这个类的对象,需要实现归档和解档的两个方法
-(void)encodeWithCoder:(NSCoder *)aCoder
{
    //如果父类有归档和解档的方法,子类需要调用
    [super encodeWithCoder:aCoder];
    
    [aCoder encodeObject:[NSNumber numberWithInt:self.attackPower] forKey:@"attackPower"];
    
}

-(id)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super initWithCoder:aDecoder])
    {
        self.attackPower = [[aDecoder decodeObjectForKey:@"attackPower"] intValue];
    }
    return self;
}
@end

Dog *dog = [[Dog alloc] init];
        dog.name = @"qu ming zen me jiu na me nan";
        dog.age = 16;
        //归档的基本原理
        path =@"/Users/student/Desktop/dog.data";
        //系统如何知道归档不同的对象呢?
        //需要对象所在的类提供两个方法
        //       如何归档
        //       如何解档
        [NSKeyedArchiver archiveRootObject:dog toFile:path];
        
        //解档
         Dog *newDog =[NSKeyedUnarchiver unarchiveObjectWithFile:path];
        //NSLog(@"nsmr = %@,age = %d",newDog.name,newDog.age);
        
        WolfDog *wd = [[WolfDog alloc] init];
        wd.name = @"路西恩";
        wd.age = 28;
        wd.attackPower = 10000;
        
        path = @"/Users/student/Desktop/wolfDog.data";
        [NSKeyedArchiver archiveRootObject:wd toFile:path];
        //解档
        WolfDog *newWd = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        NSLog(@"name = %@, age = %d, attackPower = %d",newWd.name,newWd.age,newWd.attackPower);

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。