Initializing NSDictionary

kschins picture kschins · Feb 8, 2012 · Viewed 67.9k times · Source

The following is in my .h file:

    NSDictionary *originalValues;
    @property (nonatomic, retain) NSDictionary *originalValues;

This is the .m file to init the NSDictionary.

@synthesize originalValues;

- (void)viewDidLoad {

// copy original values when view loaded
originalValues = [[NSDictionary alloc] initWithObjectsAndKeys:place.city, @"city", place.cuisine, @"cuisine",
                place.latitude, @"latitude", place.longitude, @"longitude", place.name, @"name", place.rating,
                @"rating", place.state, @"state", place.street, @"street", place.telephone, @"telephone",
                place.timesVisited, @"times visited", place.uppercaseFirstLetterOfName, @"first letter", 
                place.website, @"website", place.zipcode, @"zipcode", nil];
}

The problem is only the first four objects and keys are getting added. After that, they are not being added to the dictionary starting with place.name, @"name". I did a NSLog on the entire dictionary and the only things outputted were the first four values like I mentioned so then II did an NSLog on place.name and it is outputting a value so I know something should also be outputted for this key/value pair. Is there something I am missing here? I'm curious why all of the values are not being initially added to the NSDictionary?

Answer

TotoroTotoro picture TotoroTotoro · Dec 19, 2013

If one of the objects is nil, you can catch that much faster if you use the new literal syntax for initializing an NSDictionary (below). This syntax is not only shorter, but also more robust: you'll actually get a runtime error if one of your objects is nil, instead of silently continuing execution with the incomplete data.

originalValues = @{ @"city"     : place.city, 
                    @"latitude" : place.latitude,
                    // etc.
                  };