objective c - How can you shorten repetitive if/else statements? -
how can simplify code? gets lengthy , extremely repetitive, many null checks.
id data; data = [dictionary objectforkey:@"firstname"]; if ([data isequal:[nsnull null]]) { self.firstname = @""; } else{ self.firstname = (nsstring *)data; } data = [dictionary objectforkey:@"middlename"]; if ([data isequal:[nsnull null]]) { self.middlename = @""; } else{ self.middlename = (nsstring *)data; } data = [dictionary objectforkey:@"lastname"]; if ([data isequal:[nsnull null]]) { self.lastname = @""; } else{ self.lastname = (nsstring *)data; } ...
ideally want put variables in array of sorts, , loop through , apply null check , assignment of them. can't store variables in array. best way shorten code?
you wrap each of calls 1 method.
- (nsstring *)stringfromdictionary:(nsdictionary *) forkey:(nsstring *)key { id data = [dictionary objectforkey:key]; if ([data iskindofclass:[nsstring class]]) { return = (nsstring *)data; } else { return @""; } }
then call method 3 times.
self.firstname = [self stringfromdictionary:dictionary forkey:@"firstname"]; self.middlename = [self stringfromdictionary:dictionary forkey:@"middlename"]; self.lastname = [self stringfromdictionary:dictionary forkey:@"lastname"];
Comments
Post a Comment