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 NSDictionary
s. I now have a few options:
Make all properties on
Book
mutable (I hate this option). You could then have aBookManager
class with takes anNSArray
ofNSDictionary
s and maps the data in the dictionary to the correct properties.Add an initialiser to the
Book
object which accepts the important details.
Example:
- (instancetype)initWithTitle:(NSString *)title author:(NSString *)author publishDate:(NSDate *)publishDate;
The aforementioned BookManager
class could then take the NSDictionary
s 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.
- Add an initialiser to
Book
which accepts theNSDictionary
representation of itself. I dislike this approach in one way because I feel the responsibility is not the model's to create itself from a dictionary. I prefer the idea of a manager class mapping the dictionary to the model. However, I do like the fact that it means that all properties can bereadonly
.
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.