Search code examples
nsdictionary

A question about NSDictionary initialization


the result is 4 2 3, but what happened in the process of initialization of this NSDictionary? it's because that its assignment just execute at first time and ignore the rest assignment to same key? Or it's because that its assigment execute with Reverse order?

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"]);

Solution

  • From the documentation of 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.

    From the documentation of dictionaryWithObjects:forKeys:count:

    This method steps through the objects and keys arrays, creating entries in the new dictionary as it goes.

    The result of

    NSDictionary *dic = @{
                          @"a":@"4",
                          @"b":@"2",
                          @"c":@"3",
                          @"a":@"1",
                          @"b":@"5",
                          @"c":@"6",
    };
    

    is unpredictable and may be different in other versions of Foundation. On macOS 10.13.6 the duplicate keys are ignored.