本文主要是介绍[iOS]NSDictionary处理取出的Value为NSNull导致有闪退风险的问题,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
后端处理很多类型的数据为空时,很多时候是直接返回null,导致前端解析数据后得到的一些Value为NSNull,这将会导致程序中产生一些闪退情况。
- (void)viewDidLoad {[super viewDidLoad];NSMutableDictionary *tempDict = [NSMutableDictionary new];[tempDict setObject:[NSNull new] forKey:@"id"];// 有可能取出空(NSNull),后续操作可能导致应用程序闪退id tempValue = [tempDict objectForKey:@"id"];// 取出安全的值// id tempValue = [tempDict safeStringObjectForKey:@"id"];/**程序终止*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSNull integerValue]: unrecognized selector sent to instance 0x1b49f7878'*/[tempValue integerValue];NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];/** 程序终止*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to insert non-property list object null for key save_id'*/[defaults setObject:tempValue forKey:@"save_id"];
}
拓展NSDictionary添加一个安全的取值方法,先对获取的值进行处理后再返回。
#import <Foundation/Foundation.h>@interface NSDictionary (Expand)- (id)safeStringObjectForKey:(NSString*)key;@end#import "NSDictionary+Expand.h"@implementation NSDictionary (Expand)- (id)safeStringObjectForKey:(NSString*)key {id object = [self objectForKey:key];// 字典中没key时value为<nil>if (![[self allKeys] containsObject:key]) {object = nil;}if ([[object class] isSubclassOfClass:[NSNull class]]) {object = nil;} else if ([[object class] isSubclassOfClass:[NSNumber class]]) {// 判断NSNumber是不是小数if (([object doubleValue] - floor([object doubleValue]) < 0.01)) {object = [NSString stringWithFormat:@"%ld",(long)[object integerValue]];} else {object = [NSString stringWithFormat:@"%.2f",[object doubleValue]];}}return object;
}@end
这篇关于[iOS]NSDictionary处理取出的Value为NSNull导致有闪退风险的问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!