nullable - Nonnull violation detection in Objective-C -
i have code declare object nonnull properties
@interface helloobject : nsobject @property (nonatomic,strong,nonnull) nsstring *foo; @property (nonatomic,strong,nonnull) nsstring *bar; -(instancetype _nullable)initwithjson:(nonnull nsdictionary*)json; @end
and initialize object json make use code:
-(instancetype _nullable)initwithjson:(nonnull nsdictionary*)json { if( (self = [super init]) ) { _bar = json[@"bar"]; _foo = json[@"foo"]; } return self; }
the server may have sent me malformed json. example, "foo" field might missing. easy enough check nil , return nil, have lot of code , inelegant , error prone.
is there easy , elegant way check see if object violates nonnull declarations @ runtime? example, don't want write code this:
barx = json[@"bar"]; if (barx) { _bar = barx; } else { return nil; }
that's ugly , boilerplate (and therefore prone error). i'd rather have like:
if (![self validfornonnulls]) { return nil; }
but can't think of way write validfornonnulls general object.
i don't think trying work around need test nil
practical in objective-c.
if having verify many such incoming terms, , needed check them validity or return nil
, rewrite initwithjson
method check, category keep code clean , readable.
- (instancetype _nullable)initwithjson:(nonnull nsdictionary *)json { if ( (self = [super init]) ) { if ( ![json hasvaluesforkeys:@[@"foo", @"bar"]] ) { //consider logging error return nil; } _bar = json[@"bar"]; _foo = json[@"foo"]; } return self; } ... @interface nsdictionary (hasvaluesforkeys) - (bool)hasvaluesforkeys:(nsarray *)keys; @end @implementation - (bool)hasvaluesforkeys:(nsarray *)keys { (nsstring *key in keys) { if ( !self[key] || [self[key] isequal:[nsnull null]] ) { return no; } } return yes; } @end
you make more specific tests each value if need validate whether nsnumber
example.
Comments
Post a Comment