关于NSDictionary初始化的一个问题
A question about NSDictionary initialization
结果是4 2 3,但是这个NSDictionary在初始化的过程中发生了什么?
这是因为它的赋值只是在第一次执行而忽略了对同一个键的其余赋值?还是因为它的赋值是反序执行的?
NSDictionary *dic = @{
@"a":@"4",
@"b":@"2",
@"c":@"3",
@"a":@"1",
@"b":@"5",
@"c":@"6",
};
NSLog(@"luozhiyong,%@",dic[@"a"]);
NSLog(@"luozhiyong,%@",dic[@"b"]);
NSLog(@"luozhiyong,%@",dic[@"c"]);
来自 NSDictionary 的文档:
NSDictionary A static collection of objects associated with unique keys.
In addition to the provided initializers, such as initWithObjects:forKeys:, you can create an NSDictionary object using a dictionary literal.
NSDictionary *dictionary = @{
@"anObject" : someObject,
@"helloString" : @"Hello, World!",
@"magicNumber" : @42,
@"aValue" : someValue
};
In Objective-C, the compiler generates code that makes an underlying call to the dictionaryWithObjects:forKeys:count: method.
来自 dictionaryWithObjects:forKeys:count 的文档:
This method steps through the objects and keys arrays, creating entries in the new dictionary as it goes.
结果
NSDictionary *dic = @{
@"a":@"4",
@"b":@"2",
@"c":@"3",
@"a":@"1",
@"b":@"5",
@"c":@"6",
};
不可预测,在其他版本的 Foundation 中可能有所不同。在 macOS 10.13.6 上,重复键将被忽略。
结果是4 2 3,但是这个NSDictionary在初始化的过程中发生了什么? 这是因为它的赋值只是在第一次执行而忽略了对同一个键的其余赋值?还是因为它的赋值是反序执行的?
NSDictionary *dic = @{
@"a":@"4",
@"b":@"2",
@"c":@"3",
@"a":@"1",
@"b":@"5",
@"c":@"6",
};
NSLog(@"luozhiyong,%@",dic[@"a"]);
NSLog(@"luozhiyong,%@",dic[@"b"]);
NSLog(@"luozhiyong,%@",dic[@"c"]);
来自 NSDictionary 的文档:
NSDictionary A static collection of objects associated with unique keys.
In addition to the provided initializers, such as initWithObjects:forKeys:, you can create an NSDictionary object using a dictionary literal.
NSDictionary *dictionary = @{
@"anObject" : someObject,
@"helloString" : @"Hello, World!",
@"magicNumber" : @42,
@"aValue" : someValue
};
In Objective-C, the compiler generates code that makes an underlying call to the dictionaryWithObjects:forKeys:count: method.
来自 dictionaryWithObjects:forKeys:count 的文档:
This method steps through the objects and keys arrays, creating entries in the new dictionary as it goes.
结果
NSDictionary *dic = @{
@"a":@"4",
@"b":@"2",
@"c":@"3",
@"a":@"1",
@"b":@"5",
@"c":@"6",
};
不可预测,在其他版本的 Foundation 中可能有所不同。在 macOS 10.13.6 上,重复键将被忽略。