IOS学习笔记二十四(NSData归档多个对象和归档对象实现深复制)

简介: IOS学习笔记二十四(NSData归档多个对象和归档对象实现深复制)

1、NSData归档多个对象

一、之前我写的学习笔记都是归档一个对象,如果需要归档多个对象我们需要借助NSData

二、步骤

     1)、NSMutableData作为参数,构建 NSKeyedArchiver对象

     2)、调用NSKeyedArchiver的encodeXXX

     3)、调用NSKeyedArchiver的finishEncoding方法

     4)、NSMutableData保存到文件

2、归档对象实现深复制

  我们知道深复制就是复制对象和原始对象没有任何公用的部分,修改复制对象的值不会对原始对象产生影响。

步骤

1)、NSKeyedArchiver的archivedDataWithRootObject

2)、NSKeyedUnarchiver的unarchiveObjectWithData

3、实现Demo

IApple.h

#import <Foundation/Foundation.h>
#ifndef IApple_h
#define IApple_h
@interface IApple : NSObject <NSCoding>
@property (nonatomic, copy) NSString *color;
@property (nonatomic, assign) double weight;
@property (nonatomic, assign) int size;
-(id)initWithColor:(NSString *) color weight:(double) weight size:(int) size;
@end
#endif /* IApple_h */

IApple.m

#import  "IApple.h"
#import <Foundation/Foundation.h>
@implementation IApple
@synthesize color = _color;
@synthesize weight = _weight;
@synthesize size = _size;
-(id)initWithColor:(NSString *) color weight:(double) weight size:(int) size
{
    if (self = [super init])
    {
        self.color = color;
        self.weight = weight;
        self.size = size;
    }
    return self;
}
-(NSString *)description
{
    return [NSString stringWithFormat:@"<IApple [color = %@, weight = %g, _size = %d]>", self.color, self.weight, self.size];
}
-(void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:_color forKey:@"color"];
    [aCoder encodeDouble:_weight forKey:@"weight"];
    [aCoder encodeInt:_size forKey:@"size"];
}
-(id) initWithCoder:(NSCoder *)aDecoder
{
    _color = [aDecoder decodeObjectForKey:@"color"];
    _weight = [aDecoder decodeDoubleForKey:@"weight"];
    _size = [aDecoder decodeIntForKey:@"size"];
    return self;
}
@end

IApple.m

#import  "IApple.h"
#import <Foundation/Foundation.h>
@implementation IApple
@synthesize color = _color;
@synthesize weight = _weight;
@synthesize size = _size;
-(id)initWithColor:(NSString *) color weight:(double) weight size:(int) size
{
    if (self = [super init])
    {
        self.color = color;
        self.weight = weight;
        self.size = size;
    }
    return self;
}
-(NSString *)description
{
    return [NSString stringWithFormat:@"<IApple [color = %@, weight = %g, _size = %d]>", self.color, self.weight, self.size];
}
-(void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:_color forKey:@"color"];
    [aCoder encodeDouble:_weight forKey:@"weight"];
    [aCoder encodeInt:_size forKey:@"size"];
}
-(id) initWithCoder:(NSCoder *)aDecoder
{
    _color = [aDecoder decodeObjectForKey:@"color"];
    _weight = [aDecoder decodeDoubleForKey:@"weight"];
    _size = [aDecoder decodeIntForKey:@"size"];
    return self;
}
@end

main.m

#import "IApple.h"
int main(int argc, char * argv[]) {
    @autoreleasepool {
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:80], @"java", [NSNumber numberWithInt:90], @"c", [NSNumber numberWithInt:70], @"oc", [NSNumber numberWithInt:100], @"c++",nil];
        NSSet *set = [NSSet setWithObjects:@"java", @"ios", @"c++", @"oc", nil];
        IApple *apple = [[IApple alloc] initWithColor:@"red" weight:50 size:20];
        NSMutableData *data = [NSMutableData data];
        NSKeyedArchiver *arch = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
        //归档对象
        [arch encodeObject:dict forKey:@"dict"];
        [arch encodeObject:set forKey:@"set"];
        [arch encodeObject:apple forKey:@"apple"];
        //结束归档
        [arch finishEncoding];
        //在document目录下创建一个chenyu.txt空文件
        NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *path = [docPaths objectAtIndex:0];
        NSLog(@"document path:%@", path);
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *chenyuPath = [path stringByAppendingPathComponent:@"chenyu.txt"];
        BOOL isSuccess = [fileManager createFileAtPath:chenyuPath contents:nil attributes:nil];
        if (isSuccess) {
            NSLog(@"make chenyu.txt success");
        } else {
            NSLog(@"make chenyu.txt fail");
        }
        //归档对象到chenyu.txt文件
        if([data writeToFile:chenyuPath atomically:YES] == YES)
        {
            NSLog(@"归档对象成功");
        }
        else
        {
            NSLog(@"归档对象失败");
        }
        //读取归档对象
        NSData *readData = [NSData dataWithContentsOfFile:chenyuPath];
        NSKeyedUnarchiver *unArch = [[NSKeyedUnarchiver alloc] initForReadingWithData:readData];
        NSDictionary *readDict = [unArch decodeObjectForKey:@"dict"];
        NSSet *readSet = [unArch decodeObjectForKey:@"set"];
        NSSet *readApple = [unArch decodeObjectForKey:@"apple"];
        NSLog(@"readDict is:%@", readDict);
        NSLog(@"readSet is:%@", readSet);
        NSLog(@"readApple is %@", readApple);
        //使用归档对戏实现深复制 深复制就是复制对象和本身对象没有任何公用部分,所以修改复制对象的属性不会影响原始对象的属性
        NSDictionary *diction = [NSDictionary dictionaryWithObjectsAndKeys:[[IApple alloc] initWithColor:@"red" weight:50 size:20], @"one", [[IApple alloc] initWithColor:@"green" weight:60 size:21], @"two", nil];
        //对象归档
        NSData *data1 = [NSKeyedArchiver archivedDataWithRootObject:diction];
        //回复对象
        NSDictionary *dictCopy = [NSKeyedUnarchiver unarchiveObjectWithData:data1];
        IApple *app = [dictCopy objectForKey:@"one"];
        [app setColor:@"green"];
        IApple *app1 = [diction objectForKey:@"one"];
        NSLog(@"app1 color is:%@", app1.color);
    }
}

4、运行结果

2018-07-22 19:34:11.258816+0800 cyTest[62704:16613816] document path:*****/3FF9B833-FAF8-4C30-A855-3D40A4EAE8A6/data/Containers/Data/Application/6AD520C9-3A99-45B5-A2F9-4E4D7CA77486/Documents
2018-07-22 19:34:11.269539+0800 cyTest[62704:16613816] make chenyu.txt success
2018-07-22 19:34:11.271898+0800 cyTest[62704:16613816] 归档对象成功
2018-07-22 19:34:11.272976+0800 cyTest[62704:16613816] readDict is:{
    c = 90;
    "c++" = 100;
    java = 80;
    oc = 70;
}
2018-07-22 19:34:11.273243+0800 cyTest[62704:16613816] readSet is:{(
    "c++",
    java,
    ios,
    oc
)}
2018-07-22 19:34:11.273602+0800 cyTest[62704:16613816] readApple is <IApple [color = red, weight = 50, _size = 20]>
2018-07-22 19:34:11.274150+0800 cyTest[62704:16613816] app1 color is:red



 


相关文章
|
12月前
|
机器学习/深度学习 API iOS开发
iOS MachineLearning 系列(17)—— 几个常用的对象识别 CoreML 模型
上一篇文章中,我们介绍了几个官方的图片分类的模型,图片分类模型的应用场景在于将图片中最主要的事物进行识别,在已有的词库中找到最可能得事物。而对象识别则要更高级一些。再之前的文章,我们介绍过可以使用官方提供的API来进行矩形识别,文本识别,二维码识别以及人脸识别等,这类识别功能的特点是我们不仅可以将图片中的物体位置和尺寸分析出来,还可以对其进行类别的分类。
263 0
|
安全 数据安全/隐私保护 iOS开发
iOS小技能:【发红包】使用tweak和lua脚本结合进行实现
我们开发的大部分越狱程序,都是编译成动态链接库(`例如:介绍的越狱程序(Tweak)开发,就是动态链接库。`),然后通过越狱平台的MobileSubstrate(iOS7上叫CydiaSubstrate)来加载进入目标程序(Target),通过对目标程序的挂钩(Hook),来实现相应的功能。
269 0
|
移动开发 JavaScript weex
weex-自定义module,实现weex在iOS的本地化,js之间互相跳转,交互,传值(iOS接入weex的最佳方式)
weex-自定义module,实现weex在iOS的本地化,js之间互相跳转,交互,传值(iOS接入weex的最佳方式)
221 0
|
存储 数据处理 iOS开发
iOS开发-本地推送实现方法和数据处理方案(二)
iOS开发-本地推送实现方法和数据处理方案(二)
172 0
|
存储 数据处理 iOS开发
iOS开发-本地推送实现方法和数据处理方案(一)
iOS开发-本地推送实现方法和数据处理方案(一)
212 0
|
iOS开发
iOS开发 - 不通过import引入类名实现push或present
iOS开发 - 不通过import引入类名实现push或present
77 0
|
Android开发 iOS开发
iOS开发 - 商品详情页两种分页模式,只提供思路和实现方式。
iOS开发 - 商品详情页两种分页模式,只提供思路和实现方式。
361 0
iOS开发 - 商品详情页两种分页模式,只提供思路和实现方式。
|
存储 安全 iOS开发
iOS开发 - 继udid,Mac地址等一系列唯一标识无效后,如何用KeyChain来实现设备唯一性
iOS开发 - 继udid,Mac地址等一系列唯一标识无效后,如何用KeyChain来实现设备唯一性
410 0
iOS开发 - 继udid,Mac地址等一系列唯一标识无效后,如何用KeyChain来实现设备唯一性
|
Swift 数据安全/隐私保护 iOS开发
iOS开发 - swift通过Alamofire实现https通信
iOS开发 - swift通过Alamofire实现https通信
359 0
iOS开发 - swift通过Alamofire实现https通信
|
开发者 iOS开发
iOS开发 - 用AFNetworking实现https单向验证,双向验证
iOS开发 - 用AFNetworking实现https单向验证,双向验证
350 0
iOS开发 - 用AFNetworking实现https单向验证,双向验证