NSDictionary取值為空,程序就出現(xiàn)賦值崩潰
解決方案給NSDictionary添加一個擴展分類厢岂,對取出的value進行判空
.h文件
#import <Foundation/Foundation.h>
@interface NSDictionary (Extension)
/**
從字典里取NSInteger(內(nèi)帶判空)
@param key 字典Key值
@return NSInteger
*/
- (NSInteger)integerValueForKey:(id)key;
/**
從字典里取int(內(nèi)帶判空)
@param key 字典Key值
@return int
*/
- (int)intValueForKey:(id)key;
/**
從字典里取long long(內(nèi)帶判空)
@param key 字典Key值
@return long long
*/
- (long long)longlongValueForKey:(id)key;
/**
從字典里取BOOL(內(nèi)帶判空)
@param key 字典Key值
@return BOOL
*/
- (BOOL)boolValueForKey:(id)key;
/**
從字典里取float(內(nèi)帶判空)
@param key 字典Key值
@return float
*/
- (float)floatValueForKey:(id)key;
/**
從字典里取字符串(內(nèi)帶判空)
@param key 字典Key值
@return NSString
*/
- (NSString *)stringValueForKey:(id)key;
/**
從字典里取數(shù)組(內(nèi)帶判空)
@param key 字典Key值
@return NSArray
*/
- (NSArray *)arrayValueForKey:(id)key;
/**
從字典里取可變數(shù)組(內(nèi)帶判空)
@param key 字典Key值
@return NSMutableArray
*/
- (NSMutableArray *)mutableArrayValueForKey:(NSString *)key;
/**
從字典里取字典(內(nèi)帶判空)
@param key 字典Key值
@return NSDictionary
*/
- (NSDictionary *)dictionaryValueForKey:(id)key;
@end
.m文件
#import "NSDictionary+Extension.h"
@implementation NSDictionary (Extension)
- (NSInteger)integerValueForKey:(id)key {
id value = [self notNullValueForKey:key];
return value == nil ? 0 : [value integerValue];
}
- (int)intValueForKey:(id)key {
id value = [self notNullValueForKey:key];
return value == nil ? 0 : [value intValue];
}
- (long long)longlongValueForKey:(id)key {
id value = [self notNullValueForKey:key];
return value == nil ? 0 : [value longLongValue];
}
- (BOOL)boolValueForKey:(id)key {
id value = [self notNullValueForKey:key];
return value == nil ? NO : [value boolValue];
}
- (float)floatValueForKey:(id)key {
id value = [self notNullValueForKey:key];
return value == nil ? NO : [value floatValue];
}
- (NSString *)stringValueForKey:(id)key {
return [self notNullValueForKey:key];
}
- (NSArray *)arrayValueForKey:(id)key {
id value = [self notNullValueForKey:key];
if(![value isKindOfClass:[NSArray class]]) {
return nil;
}
return value;
}
- (NSMutableArray*)mutableArrayValueForKey:(NSString *)key {
id value = [self notNullValueForKey:key];
if(![value isKindOfClass:[NSMutableArray class]]) {
return nil;
}
return value;
}
- (NSDictionary *)dictionaryValueForKey:(id)key {
id value = [self notNullValueForKey:key];
if(![value isKindOfClass:[NSDictionary class]]) {
return nil;
}
return value;
}
#pragma mark 判斷是否null
- (BOOL)isNullValue:(id)value {
return [value isEqual:[NSNull null]];
}
- (id)notNullValueForKey:(id)key {
id value = [self objectForKey:key];
if([self isNullValue:value]) {
return nil;
}
return value;
}
@end