iphone - 数组与数组 :nil returns empty array but not documented

标签 iphone objective-c

NSArray 和 NSMutableArray 的 +arrayWithArray: 当参数为 nil 时返回空数组而不是 nil。

    NSLog(@"%@", [[NSArray arrayWithArray:nil] class]);
    NSLog(@"%@", [[NSMutableArray arrayWithArray:nil] class]);

输出:

    __NSArrayI
    __NSArrayM

但此行为并未记录在 Apple 文档中。

依赖arrayWithArray:nil 返回空数组的假设是否安全?
或者我应该像这样显式分配空数组:

    NSDictionary *dic = [[NSDictionary alloc] init];
    NSMutableArray *arr = [dic objectForKey:@"a"];
    if (!arr) {
        arr = [[NSMutableArray alloc] init];
    }

最佳答案

+arrayWithArray: 的文档说:

Creates and returns an array containing the objects in another given array.

当然,nil不是一个数组,但是[nil count]是有效的并且返回0,所以它可能被当作这里是一个空数组。

但我不会依赖这个事实并使用[[NSMutableArray alloc] init][NSMutableArray array] 创建空数组。

已添加:

如果您使用无效类型调用 +arrayWithArray:,例如一个NSString,那么程序当然会抛出异常。但是从报错信息来看

-[__NSCFConstantString count]: unrecognized selector sent to instance 0x69e4

可以看到count确实是第一个用来复制数组元素的方法。这也解释了为什么它适用于 nil

关于iphone - 数组与数组 :nil returns empty array but not documented,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12128011/

相关文章:

iphone - 初始化中的 startUpdatingLocation

iphone - NSFileProtectionCompleteUntilFirstUserAuthentication 什么时候阻止通过计算机读取文件?

javascript - 在我的 Cordova 项目中,我想在 iOS 键盘 'done' 按钮单击上触发一个功能(搜索功能)

ios - CoreData NSFetchedResultsController 排序

ios - 使用打开的 CV 使用 iPhone 应用程序查找白球

iphone - 在运行时使用 NSUserDefaults 更改 PickerView 组件的数量

objective-c - Core Data (Mac) 如何在 ID 字段上实现自增

objective-c - 背景以不同速度移动时图层之间没有协调

ios - iOS8 中的 NSMutableDictionary 顺序不同(与 iOS7 相反)

带工具栏的操作表中的 iphone uidatepicker?