• 对象归档


        //保存图片

        //1,NSDocument

        NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;

        NSString *path = [documentPath stringByAppendingString:@"/img.png"];

        //2,创建

        UIImage *image = [UIImage imageNamed:@"1.png"];

        

        //3,save

        NSData *imgData = UIImagePNGRepresentation(image);//png -> data

        

        [imgData writeToFile:path atomically:YES];

        NSLog(@"%@",path);

        

        

        

        

        

        ///////对象归档

        ////////////////复杂对象

        //1,

        Student *stu = [[Student new] autorelease];

        

        stu.name = @"name";

        stu.age = 11;

        stu.hobby = @"fff";

        

        //1,转成nsdata

        NSMutableData *mutableData = [NSMutableData data];

        

        //2,创建归档工具

        NSKeyedArchiver *archiver = [[[NSKeyedArchiver alloc] initForWritingWithMutableData:mutableData] autorelease];

        //2.3 归档

        [archiver encodeObject:stu forKey:@"stu"];

        //2,4 完成

        [archiver finishEncoding];

        

        //3,保存文件

        NSString *stuPath = [documentPath stringByAppendingString:@"/student"];

        //3,1写入

        [mutableData writeToFile:stuPath atomically:YES];

        

        

        

        

        /////4,取出

        NSData *stuData = [NSData dataWithContentsOfFile:stuPath];

        //4,1

        NSKeyedUnarchiver *unarchiver = [[[NSKeyedUnarchiver alloc] initForReadingWithData:stuData] autorelease];

        //4,2 反归档

        Student *resultStu = [unarchiver decodeObjectForKey:@"stu"];

        

        //4,3 结束

        [unarchiver finishDecoding];

        

        NSLog(@"%@,%lu,%@",resultStu.name,resultStu.age,resultStu.hobby);

        

        

        //、、、、、直接归档

        Student *s1 = [[[Student alloc] init] autorelease];

        

        s1.name = @"jj";

        s1.hobby = @"oo";

        s1.age = 11;

        

        //

        NSString *stuPath1 = [documentPath stringByAppendingString:@"/stu1"];

        [NSKeyedArchiver archiveRootObject:s1 toFile:stuPath1];

        

        //

        Student *s2 = [NSKeyedUnarchiver unarchiveObjectWithFile:stuPath1];

        NSLog(@"%@%@%lu",s2.name,s2.hobby,s2.age);

        

        

        

  • 相关阅读:
    狭隘试试
    安装django
    青岛大学开源OJ以及部署
    十三、用户名密码管理
    十二、文件权限及所属主组的修改
    十一、tar打包命令的使用
    十、文件管理、属性、查找和软硬链接
    九、系统优化方法(基础优化)
    八、系统登陆信息的显示和硬件信息等
    七、常用基础配置
  • 原文地址:https://www.cnblogs.com/iOS-mt/p/4180383.html
Copyright © 2020-2023  润新知