将nil传递给arrayWithArray的结果是什么:?

Chr*_*ner 3 cocoa objective-c nsmutablearray nsarray

当你通过会发生什么nilarrayWithArray:

假设我有以下代码:

NSMutableArray *myArray = [NSMutableArray arrayWithArray:someOtherArray];

如果someOtherArray碰巧是nil,将myArraynil或将是一个空的可变数组?

Ric*_*III 10

返回一个空数组.

示例实现+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;
}
Run Code Online (Sandbox Code Playgroud)

因此,如果arr为null,则-count返回0,没有任何内容malloc,并且没有任何内容被复制,因为发送到nil对象的消息返回该类型的默认返回值,并且不执行任何其他操作.

  • 您不应该再指望这一点,因为方法参数隐式非空。静态分析器现在会警告您这一点。 (2认同)