zoukankan      html  css  js  c++  java
  • 归档和深拷贝

      //将array归档到path路径中

     NSString *path = [@"a.plist" documentsAppend];

    [NSKeyedArchiver archiveRootObject:array toFile:path];

      //读取path路径中文件

    [NSKeyedUnarchiver unarchiveObjectWithFile:path];

     
    #pragma mark 写入多个Person的方法
    - (void)writePersons2 {
        Person *p1 = [Person personWithName:@"person" age:10];
        Person *p2 = [Person personWithName:@"name" age:11];
        
        NSMutableData *data = [NSMutableData data];
        
        // archiver负责将p1、p2塞进data中
        NSKeyedArchiver *archiver = [[[NSKeyedArchiver alloc] initForWritingWithMutableData:data] autorelease];
        
        [archiver encodeObject:person1 forKey:@"p1"];
        
        [archiver encodeObject:person2 forKey:@"p2"];
        
        // 编码结束
        [archiver finishEncoding];
        
        NSString *path = [@"persons2.plist" documentsAppend];
        // 将data写入某个文件中
        [data writeToFile:path atomically:YES];
     }
     
    #pragma mark 读取多个Person的方法
    - (void)readPersons2 {
        NSString *path = [@"persons2.plist" documentsAppend];
        
        NSData *data = [NSData dataWithContentsOfFile:path];
        
        NSKeyedUnarchiver *unarchiver = [[[NSKeyedUnarchiver alloc] initForReadingWithData:data] autorelease];
        
        Person *p = [unarchiver decodeObjectForKey:@"person1"];
        NSLog(@"%@", p);
     }
     
    #pragma mark 用归档技术实现深拷贝1
    // 缺点就是会产生临时文件
    - (void)copyPerson1 {
        Person *p1 = [Person personWithName:@"person" age:10];
        
        NSString *path = [@"p1.plist" tmpAppend];
        // 将对象p1归档到p1.plist文件中
        [NSKeyedArchiver archiveRootObject:p1 toFile:path];
        
        Person *p2 = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        
        NSLog(@"p1-地址%x-%@", p1, p1);
        NSLog(@"p2-地址%x-%@", p2, p2);
     }
     
    #pragma mark 用归档技术实现深拷贝2
    - (void)copyPerson2 {
        Person *p1 = [Person personWithName:@"person" age:10];
        
        // 将对象p1归档成一个NSData对象
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:p1];
        
        Person *p2 = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        
        NSLog(@"p1-地址%x-%@", p1, p1);
        NSLog(@"p2-地址%x-%@", p2, p2);
     }
     
     
     
     
     
     
  • 相关阅读:
    《数据库系统概论》 -- 3.2. 视图
    Uncaught SecurityError: Failed to execute 'replaceState' on 'History': A history state object with
    在node.js中使用mongose模块
    在centos7上作用mongodb
    Error: listen EADDRINUSE
    telnet: connect to address xxxxxxx: No route to host
    express-generator安装时出错,最后用VPS解决
    centos7中 npm install express 时Error: Cannot find module 'express'错误
    ubuntu1404服务器版中设置root用户
    python爬虫(1)
  • 原文地址:https://www.cnblogs.com/wangshengl9263/p/3050932.html
Copyright © 2011-2022 走看看