Search code examples
c++objective-cnsmutabledictionarystdmap

Difference between access operator of NSMutableDictionary and std::map


Does objective-c create a new entry when the key is not in the dictionary but accessed? Like in std::map operator[].

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSMutableDictionary<NSNumber *, NSString *> *D = [NSMutableDictionary new];
        D[@10] = @"ten";
        if (D[@1] == nil) // will it create an entry for D[@1]?
          NSLog(@"Found with nil");
    }
    return 0;
}

Solution

  • I think the answer is NO. You can check it by the below code.

    int main(int argc, char * argv[]) {
      @autoreleasepool {
        NSMutableDictionary<NSNumber *, NSString *> *D = [NSMutableDictionary new];
        D[@10] = @"ten";
        NSLog(@"%@", D); // { 10 = ten; } logged
        if (D[@1] == nil) // will it create an entry for D[@1]?
          NSLog(@"%@", D); // { 10 = ten; } logged. @1 key doesn't exist
      }
    }
    

    Beside of it, you should take a look at Apple document for objectForKey: method.

    The value associated with aKey, or nil if no value is associated with aKey.

    D[@1] is syntax sugar of [D objectForKey:@1]. So according to the document, it will return nil if no value is associated with key 1. That's why D[@1] == nil