Infinity James
Infinity James

Reputation: 4735

Creating a Model Object with an NSDictionary

This is something I have been playing with, and have yet to make my mind up about.

When querying a database, it is extremely common that you will use the data in the response to create custom model objects. Let's use 'Book' as an example.

I have received JSON describing multiple Book objects. I parse the JSON into an NSArray of NSDictionarys. I now have a few options:

Example:

- (instancetype)initWithTitle:(NSString *)title author:(NSString *)author publishDate:(NSDate *)publishDate;

The aforementioned BookManager class could then take the NSDictionarys as before, but create the Book objects with this initialiser. This is nice, because you could then make all of the public facing properties on Book readonly. However, it is very limited, and if (as is often the case) there are a lot of properties on the model, this is not feasible.

There is no doubt in my mind I am missing other options, and if you are aware of them, please point them out. The aim of this question is to finally determine the best way to approach this scenario.

Upvotes: 1

Views: 990

Answers (2)

Jamie McDaniel
Jamie McDaniel

Reputation: 1808

I regularly use an init method with the important arguments, but yes, it becomes very unwieldily when the number of arguments reach double digits and/or several of the arguments can be nil. The longest such method I have seen in the iOS SDK is CLLocation's

- (id)initWithCoordinate:(CLLocationCoordinate2D)coordinate
                altitude:(CLLocationDistance)altitude
      horizontalAccuracy:(CLLocationAccuracy)hAccuracy
        verticalAccuracy:(CLLocationAccuracy)vAccuracy
                  course:(CLLocationDirection)course
                   speed:(CLLocationSpeed)speed
               timestamp:(NSDate *)timestamp

Regarding your last option, adding an initWithDictionary: method to Book could be expanded to also include a class-level method for creating instances of Book from an NSDictionary.

+ (instancetype)bookWithDictionary:(NSDictionary *)dictionary

And optionally a convenient way to get a dictionary representation from a Book instance.

- (NSDictionary *)dictionaryRepresentation

If you search the iOS documentation for "withDictionary" and "dictionaryRepresentation" you will see a few places where this is used. In other SDKs, you will sometimes see the method named as someObjectFromDictionary:

Upvotes: 1

Related Questions