zoukankan      html  css  js  c++  java
  • 对象归档

        //保存图片

        //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);

        

        

        

  • 相关阅读:
    RT-Thread代码启动过程与$Sub$ $main、$Super$ $main
    软件开源许可证
    git回退到历史版本以及再滚回去
    GMT、UTC、UNIX时间戳、时区
    sprintf的使用
    C# Json 和对象的相互转换
    获取指定年份/月份的周六周天 + 标记指定日期(加粗)
    Winform 窗体实现圆角展示
    VS2012统计代码量
    C# Winform 中使用FTP实现软件自动更新功能
  • 原文地址:https://www.cnblogs.com/iOS-mt/p/4180383.html
Copyright © 2011-2022 走看看