当你传递nil给时会发生什么arrayWithArray:?
假设我有以下代码:
NSMutableArray *myArray = [NSMutableArray arrayWithArray:someOtherArray];
如果someOtherArray碰巧是nil,将myArray是nil还是将是一个空的可变数组?
当你传递nil给时会发生什么arrayWithArray:?
假设我有以下代码:
NSMutableArray *myArray = [NSMutableArray arrayWithArray:someOtherArray];
如果someOtherArray碰巧是nil,将myArray是nil还是将是一个空的可变数组?
返回一个空数组。
的示例实现+arrayWithArray:如下:
+(id) arrayWithArray:(NSArray *) arr
{
NSMutableArray *returnValue = [NSMutableArray new];
returnValue->objectsCount = [arr count];
returnValue->objectsPtr = malloc(sizeof(id) * returnValue->objectsCount);
[arr getObjects:returnValue->objectsPtr range:NSMakeRange(0, returnValue->objectsCount)];
return returnValue;
}
因此,如果arr为 null,则-count返回 0,没有malloc'd,并且没有任何内容被复制,因为发送到 nil 对象的消息返回该类型的默认返回值,并且不执行任何其他操作。