简体   繁体   中英

NSDictionary refuses to set values for its keys.

I have a method updateUserPlaceDictionary that draws text from some text fields and throws it in an NSDictionary. After noticing that all the values for the dictionary were null, i tried manually setting some strings for its keys, like so:

- (void)updatePlaceDictionary {
    //Create a dictionary that holds the location data.
    [self.placeDictionary setValue:[NSString stringWithFormat:@"155 Bovet Rd"] forKey:@"Street"];
    [self.placeDictionary setValue:[NSString stringWithFormat:@"san mateo"] forKey:@"City"];
    [self.placeDictionary setValue:[NSString stringWithFormat:@"ca"] forKey:@"State"];
    [self.placeDictionary setValue:[NSString stringWithFormat:@"94402"] forKey:@"ZIP"];

    NSLog(@"%@, %@, %@, %@", [self.placeDictionary objectForKey:@"Street"],
          [self.placeDictionary objectForKey:@"City"],
          [self.placeDictionary objectForKey:@"State"],
          [self.placeDictionary objectForKey:@"ZIP"]);
}

Here is my declaration of placeDictionary :

@property NSMutableDictionary* placeDictionary;

Also, i did make sure to synthesize it in the .m file.

I have the method log to the console all the location data that was put into the dictionary but all I get are null values. I have the same exact function in another view controller that works completely fine. Can someone tell me if they see anything improper?

You have a comment stating

//Create a dictionary that holds the location data.

but you never actually create it. Initialize the dictionary and you'll be fine.

self.placeDictionary = [NSMutableDictionary dictionary];

Also beware: setValue:forKey: is not the same as setObject:forKey: . Read this answer to know more on the subject, but in general you should use setObject:forKey: for dictionaries, eg

[self.placeDictionary setObject:@"155 Bovet Rd" forKey:@"Street"];

or the modern version of the syntax:

self.placeDictionary[@"Street"] = @"155 Bovet Rd";

Using Objective-C literals you can actually make the whole code a lot nicer, check it out:

self.placeDictionary = @{
    @"Street": @"155 Bovet Rd",
    @"City"  : @"san mateo",
    @"State" : @"ca",
    @"ZIP"   : @"94402"
};

Please note that the literal syntax produces a non-mutable dictionary and it may not fit your needs.

As a final remark, please don't use

[NSString stringWithFormat:@"aString"]

since is semantically equivalent to

@"aString"

but less optimized in terms of performances (not to mention code quality).

It seems as you didn't allocate it, you can do it in the getter.

-(NSMutableDictionary *)placeDictionary
{
    if (!_placeDictionary) {
        _placeDictionary = [NSMutableDictionary dictionary];
    }
    return _placeDictionary;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM