当你将 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
没有任何内容,也没有任何内容被复制,因为一条消息发送到 nil 对象返回该类型的默认返回值,并且不执行任何其他操作。
关于objective-c - 将 nil 传递给 arrayWithArray :? 的结果是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10710990/