NSDictionary取值为空,程序就出现赋值崩溃
解决方案给NSDictionary添加一个扩展分类,对取出的value进行判空
.h文件
#import <Foundation/Foundation.h>
@interface NSDictionary (Extension)
/**
从字典里取NSInteger(内带判空)
@param key 字典Key值
@return NSInteger
*/
- (NSInteger)integerValueForKey:(id)key;
/**
从字典里取int(内带判空)
@param key 字典Key值
@return int
*/
- (int)intValueForKey:(id)key;
/**
从字典里取long long(内带判空)
@param key 字典Key值
@return long long
*/
- (long long)longlongValueForKey:(id)key;
/**
从字典里取BOOL(内带判空)
@param key 字典Key值
@return BOOL
*/
- (BOOL)boolValueForKey:(id)key;
/**
从字典里取float(内带判空)
@param key 字典Key值
@return float
*/
- (float)floatValueForKey:(id)key;
/**
从字典里取字符串(内带判空)
@param key 字典Key值
@return NSString
*/
- (NSString *)stringValueForKey:(id)key;
/**
从字典里取数组(内带判空)
@param key 字典Key值
@return NSArray
*/
- (NSArray *)arrayValueForKey:(id)key;
/**
从字典里取可变数组(内带判空)
@param key 字典Key值
@return NSMutableArray
*/
- (NSMutableArray *)mutableArrayValueForKey:(NSString *)key;
/**
从字典里取字典(内带判空)
@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
网友评论