前言
小编近几年开发或面试中,自己或同事趟过的关于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