安全的从字典中取值

nsobject或者字典的类目中实现

- (NSDictionary *)dictForKey:(NSString *)key{
    if (![self isKindOfClass:[NSDictionary class]] || !key.hasValue) {
        return @{};
    }else{
        NSDictionary * dic = (NSDictionary *)self;
        NSDictionary * value = [dic objectForKey:key];
        if (!value || ![value isKindOfClass:[NSDictionary class]]) {
            return @{};
        }
        return value;
    }
}
- (NSArray *)arrForKey:(NSString *)key{
    if (![self isKindOfClass:[NSDictionary class]] || !key.hasValue) {
        return @[];
    }else{
        NSDictionary * dic = (NSDictionary *)self;
        NSArray * value = [dic objectForKey:key];
        if (!value || ![value isKindOfClass:[NSArray class]]) {
            return @[];
        }
        return value;
    }
}
- (NSString *)stringForKey:(NSString *)key{
    if (![self isKindOfClass:[NSDictionary class]] || !key.hasValue) {
        return @"";
    }else{
        NSDictionary * dic = (NSDictionary *)self;
        NSString * value = [dic objectForKey:key];
        if (!value || ![value isKindOfClass:[NSString class]]) {
            if ([value isKindOfClass:[NSNumber class]])
            {
                return ((NSNumber *)value).stringValue;
            }
            return @"";
        }
        return value;
    }
}

你可能感兴趣的:(安全的从字典中取值)