OC的数组中添加 nil 对象会有什么问题
2018-06-01 本文已影响20人
打碟的DJ
当OC的可变数组(NSMutableArray)添加 nil 对象时,首先会弹出警告 “Null passed to a callee that requires a non-null argument”,也就是说不能数组不能传递非空参数。
提示信息如下:
![](https://img.haomeiwen.com/i1428991/cf91a18053dc3f10.png)
运行后会崩溃,崩溃信息如下:
![](https://img.haomeiwen.com/i1428991/d1c162e3599856cb.png)
当OC的不可变数组(NSArray)字面量方法添加nil对象时,会报错“Collection element of type 'void *' is not an Objective-C object”
报错界面如下:
![](https://img.haomeiwen.com/i1428991/56f6289f754ff48e.png)
当用arrayWithObjects/initWithObjects时,末尾都会有个nil,因为数组元素不确定,因此要加nil,同时此时的nil也是数组结束的标识符
![](https://img.haomeiwen.com/i1428991/4b8ce4dcf0e0e04a.png)
当这种写法的时候 NSArray *array = [NSArray arrayWithObjects:@"1",@"2",nil,@"3"]; 会提示“Missing sentinel in method dispatch”,也就是提示缺少nil来结束数组
![](https://img.haomeiwen.com/i1428991/2f8195c130f65fc9.png)
当fix后会变成如下,但是数组array是以第一个nil结束的,也就是说3并不是数组中的元素
![](https://img.haomeiwen.com/i1428991/c828fd9656803a8d.png)