对于NSMutableArray用什么修饰一直都是懵的状态,有人告诉我用strong,用copy会crash,但是我自己试了一下,并没有崩溃,而且数组类型都为NSMutableArray类型
#import "ViewController.h"
@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic ,copy)NSMutableArray * mutableArray;
@property (nonatomic ,strong)NSMutableArray * stongArr;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableArray * copyArray=[[NSMutableArray alloc]init];
_mutableArray=copyArray;
_stongArr=copyArray;
[_mutableArray addObject:@"1"];
[_stongArr addObject:@"2"];
NSLog(@"当前类型%@---%@",[_mutableArray class],[_stongArr class]);
//打印结果: 当前类型__NSArrayM---__NSArrayM
但是通过copy另一个数组进行.copy赋值后会改变数组类型,将NSMutableArray转换为NSArray,因为NSArray没有NSMutableArray的方法,才会出现crash。具体代码如下:
#import "ViewController.h"
@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic ,copy)NSMutableArray * dataArray;//个人感觉这里用strong或者copy好像没啥影响
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self creatUI];
_dataArray=[[NSMutableArray alloc]initWithObjects:@"1",@"2", nil];//创建可变数组并赋值
NSMutableArray * copyArray=[[NSMutableArray alloc]init];
copyArray=_dataArray.copy;
[copyArray addObject:@"3"];//代码会在这一行出现crash,原因是因为当前数组为NSArray类型,不可使用NSMutableArray的方法。
NSLog(@"当前类型%@",[_dataArray class]);
}
可变数组进行copy操作后类型转变为NSArray.png
#import "ViewController.h"
@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic ,copy)NSMutableArray * dataArray;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self creatUI];
_dataArray=[[NSMutableArray alloc]initWithObjects:@"1",@"2", nil];//创建可变数组并赋值
NSMutableArray * copyArray=[[NSMutableArray alloc]init];
copyArray=_dataArray.mutableCopy;
[copyArray addObject:@"3"];
NSLog(@"当前类型%@",[_dataArray class]);
}
可变数组进行mutableCopy操作后,类型不变.png
以下是对copy关键字的总结:
copy对数组的影响.png虽然自己试了一下,但是最后用什么修饰还是没完全弄明白,希望有人可以准确的告诉我一下,谢谢~😢😢😢😢😢
欢迎指正~~~
网友评论