shah1988
shah1988

Reputation: 2684

Proper practice of filling a model class in iPhone

I have a simple doubt in the process of populating my model class. I get a web service response that has a jsonDictionary with 10 - 15(it can be any figure)keyValue pairs in it. I normally used to parse this jSON to an NSDictionary using another parser class and I fill in the model class from the view controller using the NSDictionary. But recently I saw in another code. The NSDictionary created from parsing the JSON string, is passed to a class that has static methods. And the model is filled from within the static method in that class as shown below

Class Name: ModelMaker

Static methods eg:

+ (MyModel1 *)fillInMyModelFromDictionay:(NSDictionary *)myDictionary;
+ (MyModel2 *)fillInMyModel2FromDictionay:(NSDictionary *)myDictionary2;

+(MyModel1 *)fillInMyModelFromDictionay:(NSDictionary *)myDictionary 
{
    MyModel1 *myModel1 = [[MyModel1 alloc] init];
    myModel1.name = [myDictionary objectForKey:@"name"];
    myModel1.age = [myDictionary objectForKey:@"age"];
    return myModel1;
}

So which approach do you think is a better one. Filling my model object from within the view controller itself or using a class as I have shown above, whose sole purpose is to fill in the model objects.

Upvotes: 2

Views: 101

Answers (2)

Koolala
Koolala

Reputation: 347

One option (option#1) is to use initWithDictionary in your model class, which is fine. The option in your question (option#2) is really a parser which has higher view of all the models so it's more flexible when a model's properties need to be populated from different data sources (eg. different json reponse)... I think option#2 is a good practice. However, if your model is simple and json structure can match your model then can always use option#1.

Upvotes: 0

Gianluca Tranchedone
Gianluca Tranchedone

Reputation: 3598

If the keys in your dictionary match the property names of your model object you can use the NSObject method - (void)setValuesForKeysWithDictionary:(NSDictionary *)keyedValues that will do all the work for you. If some of the keys do not match you can still use that method but in the model class you need to override - (id)valueForUndefinedKey:(NSString *)key.

For more informations check the Key-Value Coding Programming Guide.

Upvotes: 7

Related Questions