Haider Haider - 1 year ago 99
iOS Question

JSONModel - Assign value of JSONModel property using other properties in same JSONModel

Here's my JSON data

[{
"id": 1,
"name":"Soup",
"price1":100,
"price2":10,
},
{
"id": 2,
"name":"Salad",
"price1":100,
"price2":10,
}]


I created JSONModel as follows

@interface ProductModel : JSONModel
@property (assign, nonatomic) int id;
@property (strong, nonatomic) NSString* name;
@property (assign, nonatomic) float price1;
@property (assign, nonatomic) float price2;
@property (assign, nonatomic) BOOL isOK;
@property (assign, nonatomic) float<Optional> total; // not coming
@end


In viewcontroller

NSArray* models = [ProductModel arrayOfModelsFromDictionaries:objects];


Now what I want is

if(isOK)
{
total = price1 + price2;
} else {
total = price1 - price2;
}


Is it possible to write this logic somewhere within the model file, without iterating the model array in viewcontroller and assigning the value of total

Answer Source

My suggestion is that you create a getter for the total property in your ProductModel class.

-(float) total
{
   if(self.isOK)
   {
      return self.price1 + self.price2;
   } else {
      return self.price1 - self.price2;
   }
}