How to add to an NSDictionary

前端 未结 6 1348
无人及你
无人及你 2020-12-12 19:00

I was using a NSMutableArray and realized that using a dictionary is a lot simpler for what I am trying to achieve.

I want to save a key as a NSSt

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-12 19:25

    By setting you'd use setValue:(id)value forKey:(id)key method of NSMutableDictionary object:

    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    [dict setValue:[NSNumber numberWithInt:5] forKey:@"age"];
    

    Or in modern Objective-C:

    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    dict[@"age"] = @5;
    

    The difference between mutable and "normal" is, well, mutability. I.e. you can alter the contents of NSMutableDictionary (and NSMutableArray) while you can't do that with "normal" NSDictionary and NSArray

提交回复
热议问题