Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing NSDictionary

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?

like image 877
kschins Avatar asked Feb 08 '12 14:02

kschins


People also ask

What is NSDictionary in Objective-C?

Overview. The NSDictionary class declares the programmatic interface to objects that manage immutable associations of keys and values. For example, an interactive form could be represented as a dictionary, with the field names as keys, corresponding to user-entered values.

How do I know if NSDictionary is empty?

Every number that is 0 equals to @NO . Every number that is not 0 equals to @YES . Therefore you can just pass the count into the if .

How do you convert NSDictionary to NSMutableDictionary?

Use -mutableCopy . NSDictionary *d; NSMutableDictionary *m = [d mutableCopy]; Note that -mutableCopy returns id ( Any in Swift) so you will want to assign / cast to the right type. It creates a shallow copy of the original dictionary.


1 Answers

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.                   }; 
like image 101
TotoroTotoro Avatar answered Sep 19 '22 21:09

TotoroTotoro