//聯(lián)系人:石虎QQ: 1224614774昵稱:嗡嘛呢叭咪哄
一、代碼實(shí)現(xiàn)數(shù)組賦值不用copy數(shù)據(jù)分析
#import"ViewController.h"
@interfaceViewController()
@property(nonatomic,strong)NSArray*array;//全局不可變數(shù)組
@end
@implementationViewController
- (void)viewDidLoad {
[superviewDidLoad];
NSMutableArray*mArray = [NSMutableArrayarray];
[mArrayaddObject:@"shihu"];
self.array= mArray;
[mArrayaddObject:@"zhangying"];
NSLog(@"self.array --->%@ ,mArray --> %@",self.array,mArray);
}
提問:大家猜猜控制器會(huì)輸出什么數(shù)據(jù)???
打印結(jié)果:
2017-09-10 12:19:28.300找bug~demo[74440:1165432] self.array --->(
shihu,
zhangying
) ,mArray --> (
shihu,
zhangying
)
原因很簡單, 因?yàn)镺bjective-C支持多態(tài).
所以表面上self.array是NSArray對象, 其實(shí)骨子里是NSMutableArray對象.這樣的話將會(huì)對后期DEBUG增加很大的成本, 可能會(huì)導(dǎo)致莫名其妙的錯(cuò)誤.
二谷遂、用copy數(shù)據(jù)分析
- (void)viewDidLoad {
[superviewDidLoad];
NSMutableArray*mArray = [NSMutableArrayarray];
[mArrayaddObject:@"shihu"];
//self.array = mArray;
self.array= [mArraycopy];//淺拷貝一次
[mArrayaddObject:@"zhangying"];
NSLog(@"self.array --->%@ ,mArray --> %@",self.array,mArray);
}
提問:大家猜猜控制器會(huì)輸出什么數(shù)據(jù)???
打印結(jié)果:
2017-09-10 12:25:27.720找bug~demo[74493:1169444] self.array --->(
shihu
) ,mArray --> (
shihu,
zhangying
)
結(jié)論:這樣就能保證不管賦值的是可變還是不可變數(shù)組, NSArray就是NSArray了
三执泰、補(bǔ)充圖表更加理解copy與mutableCopy的區(qū)別:
圖1: