当前位置:网站首页>OC-拷贝
OC-拷贝
2022-08-04 21:37:00 【彭同学她同桌】
深拷贝
地址会发生改变
NSString* s1 = [NSString stringWithFormat:@"abcd"];
NSString* s2 = [s1 mutableCopy];//此时s2地址变了 但是s2依旧时不可变对象
NSMutableString *s3 = [s1 mutableCopy];//这样就可以
[s3 appendString:@"" ]
浅拷贝 指针拷贝
地址不会发生改变
NSString* s2 = [s1 copy];//地址是不会变的
NSString* s1 = [NSString stringWithFormat:@"abcd"];
NSString* s2 = [s1 copy];
NSLog(@"%p,%p",s1,s2);//会发现地址一样
如果想要调用copy就需要实现copyWithZone并且使用NSCopying协议(这个协议里面有copyWithZone)
自定义copy
@interface B:NSObject<NSCopying>
@property (copy)NSString *name;
@end
@implementation B
-(id)copyWithZone:(NSZone *)zone//这样重写后在A类中就能实现b变量的深拷贝
{
B* temp = [[B alloc]init];
temp.name = _name;
return temp;
}
@end
@interface A:NSObject<NSCopying>
@property (copy)NSString *name;//深拷贝 通过这个可以决定这个变量是深拷贝还是浅拷贝
/* 如果是copy 则setName的实现是 -(void)setName:(NSString*)name { _name = [name copy];//此时无论是可变(NSMutableString)还是不可变(NSString)copy得到的都是不可变对象 } */
@property (strong)NSString *name1;//浅拷贝
@property (nonatomic,strong)B*b;//如果重写了b的copyWithZone 则可以实现深拷贝
@end
@implementation A
-(id)copyWithZone:(NSZone *)zone
{
NSLog(@"执行了copyWithZone");
A *temp = [[A alloc]init];
temp.name = _name;//此时是浅拷贝 地址不会发生改变相当于执行[_name copy]
temp.name1 = _name1; //同样地址不会变 并且在外面改变temp.name1 也会对_name1座更改
temp.b = [_b copy];//这里copy实现深拷贝 temp.b和_b的地址就不一样了
return temp;
}
不可变对象执行copy生成的还是不可变对象 指针拷贝 浅拷贝
不可变对象执行mutableCopy 生成了可变对象 内容拷贝 深拷贝
可变对象执行copy 生成不可变对象 但是时深拷贝 地址会改变
可变对象执行mutableCopy 生成可变对象 深拷贝 地址会改变
边栏推荐
猜你喜欢

In which industries is the PMP certificate useful?

OD-Model【6】:YOLOv2

Red team kill-free development practice of simulated confrontation

LayaBox---TypeScript---Problems encountered at first contact

【uiautomation】微信好友列表获取(存储到txt中)

C language knowledge (1) - overview of C language, data types

Altium Designer 19.1.18 - Protecting Locked Objects

七夕特制:《牛郎会织女》

AXI interface application of Zynq Fpga image processing - the use of axi_lite interface

buu web
随机推荐
stm32mp157系统移植 | 移植ST官方5.10内核到小熊派开发板
如何将二叉搜索树转化为一个有序的双向链表(原树上修改)
经验分享|盘点企业进行知识管理时的困惑类型
How to solve the problem that the alarm information cannot be transmitted after EasyGBS is connected to the latest version of Hikvision camera?
基于 Milvus 和 ResNet50 的图像搜索(部署及应用)
OD-Model [6]: YOLOv2
数电快速入门(三)(卡诺图化简法的介绍)
Ramnit感染型病毒分析与处置
docker 搭建mysql 主从复制
Three ways to set a specific device UWP XAML view
Excel商业智能-Power BI电商数据分析实战
moke、动态图片资源打包显示
Yolov7:Trainable bag-of-freebies sets new state-of-the-art for real-time objectdetectors
"Jianzhi offer" brush title classification
LayaBox---知识点
27. Dimensionality reduction
PRIMAL: Pathfinding via Reinforcement and Imitation Multi-Agent Learning Code Analysis
PMP证书在哪些行业有用?
Qiangwang Cup 2022 - WEB
JdbcTemplate概述和测试