iOS 中关于Copy的疑问汇总

前言

小编近几年开发或面试中,自己或同事趟过的关于Copy的坑,现收集汇总如下:


疑问代码

// 有的人用 strong 有的用copy
@interface ViewController ()
@property (nonatomic, strong) NSString *str;
@end
// 深浅Copy 啥区别,下面代码是深了还是浅了 ?
NSMutableString *mutStr = [NSMutableString stringWithFormat:@"zyy"];
NSString *aCopyStr = [mutStr copy];
// 怎么没见过这样写代码的?
@interface ViewController ()
@property (nonatomic, copy) UIView *aCopyView;
@end
// 容器本身和容器内元素 都是深拷贝吗?
@interface ViewController ()
@property (nonatomic, copy) NSMutableArray *aCopyArray;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSMutableArray  *mutArray = [[NSMutableArray alloc] init];
    NSMutableString *mstr1 = [[NSMutableString alloc]initWithString:@"zyy1"];
    NSMutableString *mstr2 = [[NSMutableString alloc]initWithString:@"zyy2"];
    [mutArray addObject:mstr1];
    [mutArray addObject:mstr2];
    self.aCopyArray = mutArray;
}
// 2个协议和copy、mutableCopy 啥关系? 为什么数组、字典、字符串 都遵守了这2个协议
@protocol NSCopying

- (id)copyWithZone:(nullable NSZone *)zone;

@end

@protocol NSMutableCopying

- (id)mutableCopyWithZone:(nullable NSZone *)zone;

@end

Crash崩溃代码示例

@interface ViewController ()
@property (nonatomic, copy) NSMutableArray *mutableArray;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSMutableArray *array = [NSMutableArray arrayWithObjects:@"1",@"2",nil];
    self.mutableArray = array;
    [self.mutableArray removeObjectAtIndex:0];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    NSMutableString *string = [NSMutableString stringWithString: @"origin"];
    NSMutableString *mStringCopy = [string copy];
    NSMutableString *stringMCopy = [string mutableCopy];
    [mStringCopy appendString:@"mm"];
    [stringMCopy appendString:@"!!"];
}
@interface ViewController ()
@property (nonatomic, copy) UIView *aCopyView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.aCopyView = [[UIView alloc] init];
}

正确答案

// 待补充,后续更新。


感谢

如果你对以上代码有不解的地方,请查看我这篇博客(点击 iOS中的Copy(传送门)) 或许对你有所帮助。

最后,感谢感谢大家的阅读,希望对您有所帮助。如果有错误的地方或者不理解的地方,希望大家在评论区积极指出。如果对您有所帮助,希望给作者点个赞,您的支持是我最核心的动力。

也欢迎大家提出自己在工作或者面试中 趟过的关于Copy的一些坑,欢迎给我留言,小编后续一起更新上。

更多iOS技术交流
请加群: 553633494

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值