3

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

Haider
  • 4,961
  • 2
  • 18
  • 25

2 Answers2

3

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;
   }
}
ppaulojr
  • 3,579
  • 4
  • 29
  • 56
2
  • Declare a read-only property in ProductModel

    @property (assign, nonatomic, readonly) float total;
    
  • And implement it

    - (float)total
    {
       return (self.isOK) ? self.price1 + self.price2 : self.price1 - self.price2;
    }
    

Then you can read the value simply with the syntax model.total

vadian
  • 274,689
  • 30
  • 353
  • 361