NSDictionary dictionaryWithObjectsAndKeys vs文字符号

时间:2016-01-04 01:37:43

标签: objective-c

使用NSDictionary / NSArray构造函数和文字符号有什么区别?

NSDictionary *dict1 = [NSDictionary dictionaryWithObjectsAndKeys:@"bar", @"foo"];
NSDictionary *dict2 = @{ @"foo" : @"bar" };

NSArray *arr1 = [NSArray arrayWithObject:@"one", @"two"];
NSArray *arr2 = @[ @"one", @"two" ];

访问字典和数组元素怎么样?

NSLog(@"%@", [dict1 objectForKey:@"foo"]);
NSLog(@"%@", dict2[@"foo"]);

NSLog(@"%@", [arr1 objectAtIndex:0]);
NSLog(@"%@", arr2[0]);

差异是纯粹的可读性,还是性能/行为差异?

1 个答案:

答案 0 :(得分:2)

正如in the Clang documentation所述,文字@{}@[]表单与dictionaryWithObjects:forKeys:count:arrayWithObjects:count:相同,后者验证没有nil值在场。

同样,下标符号直接转换为objectAtIndexedSubscript: / setObject:atIndexedSubscript:objectForKeyedSubscript: / setObject:forKeyedSubscript:(如果您愿意,可以为您自己的类实现)。< / p>

编译此代码......

@import Foundation;
int main() {
    NSDictionary *dict1 = [NSDictionary dictionaryWithObjectsAndKeys:@"bar", @"foo", nil];
    NSDictionary *dict2 = @{@"foo" : @"bar"};
    NSString *result1 = dict2[@"bar"];

    NSArray *arr1 = [NSArray arrayWithObjects:@"one", @"two", nil];
    NSArray *arr2 = @[@"one", @"two"];
    NSString *result2 = arr2[1];
    return 0;
}

...用Hopper打开二进制文件会显示这个伪代码,这个伪代码并不完美,但足以看出发生了什么:

pseudocode