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

        

        

        

  • 相关阅读:
    (转)【web前端培训之前后端的配合(中)】继续昨日的故事
    ural(Timus) 1136. Parliament
    scau Josephus Problem
    ACMICPC Live Archive 6204 Poker End Games
    uva 10391 Compound Words
    ACMICPC Live Archive 3222 Joke with Turtles
    uva 10132 File Fragmentation
    uva 270 Lining Up
    【转】各种字符串哈希函数比较
    uva 10905 Children's Game
  • 原文地址:https://www.cnblogs.com/iOS-mt/p/4180383.html
Copyright © 2011-2022 走看看