Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make primitive type properties Optional?

Tags:

jsonmodel

I want to make some primitive properties option in my JSONModel classes. Please see the code below.

#import "JSONModel.h"

@protocol GreenModel <NSObject>
@end

@interface MyModel : JSONModel

@property (nonatomic, assign) NSInteger<Optional> objId;
@property (nonatomic, strong) NSString *name;
@end

Can anybody suggest a way to achieve this?

like image 846
Aruna Avatar asked Feb 14 '14 11:02

Aruna


2 Answers

You can do this by using propertyIsOptional:. Just return YES for the names of the properties you want to make Optional.

https://github.com/icanzilb/JSONModel#make-all-model-properties-optional-avoid-if-possible

+(BOOL)propertyIsOptional:(NSString*)propertyName
{
  if ([propertyName isEqualToString: @"objId"]) return YES;
  return NO;
}
like image 56
Marin Todorov Avatar answered Oct 20 '22 05:10

Marin Todorov


For swift

Please use following code in the sub class of your JSON model. If you want to give all the properties as optional then the code will looks like this:

override class func propertyIsOptional(propertyName: String!) -> Bool    {
   return true
}    

If you want a specific property the code will looks like this:

override class func propertyIsOptional(propertyName: String!) -> Bool     {
if propertyName == "your_property_name"
{
    return true
}
    return false
}
like image 32
Tyson Vignesh Avatar answered Oct 20 '22 06:10

Tyson Vignesh