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

标签 objective-c cocoa nsmutablearray nsarray

当你将 nil 传递给 arrayWithArray: 时会发生什么?

假设我有以下代码:

NSMutableArray *myArray = [NSMutableArray arrayWithArray:someOtherArray];

如果 someOtherArray 恰好是 nilmyArray 会是 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/

相关文章:

ios - 如何在 Objective C 和 swift Viewcontroller 中使用委托(delegate)

objective-c - 不使用时自动隐藏工具栏

ios - 需要帮助弄清楚为什么我的 UIImageView 不会缩放/平移 - 包含代码片段

iphone - 将对象插入到使用 NSUserDefaults 保存的 NSMutableArray 中

objective-c - 遍历NSMutableArray

ios - 从多维 NSDictionary 的子字典值创建排序数组

iphone - Objective-C : Multiple delegates

iphone - 当有人给您打电话/发短信时暂停游戏

ios - XCode 7 和 Swift 混淆

cocoa-touch - 如何在 NSString 中添加不间断空格?