你怎么能缩短重复的if / else语句?

时间:2015-06-02 18:40:57

标签: objective-c

如何简化此代码?它变得非常冗长并且非常重复,有很多空检查。

    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;
    }

    ...

理想情况下,我希望将所有变量放在一个排序数组中,然后循环遍历并对所有变量应用null检查和赋值。但是你无法将变量存储在数组中。缩短此代码的最佳方法是什么?

2 个答案:

答案 0 :(得分:4)

您可以将每个调用包装成一个方法。

- (NSString *)stringFromDictionary:(NSDictionary *) forKey:(NSString *)key 
{
    id data = [dictionary objectForKey:key];
    if ([data isKindOfClass:[NSString class]]) {
        return = (NSString *)data;
    } else {
        return @"";
    }
}

然后调用该方法三次。

self.firstName = [self stringFromDictionary:dictionary forKey:@"FirstName"];
self.middleName = [self stringFromDictionary:dictionary forKey:@"MiddleName"];
self.lastName = [self stringFromDictionary:dictionary forKey:@"LastName"];

答案 1 :(得分:1)

您可以使用三元运算符来缩短代码

self.firstName = [data isEqual:[NSNull null]] ? @"" : (NSString *)data;