本文介绍了如何在iOS中捕获异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在JSON解析中,将解析数据保存到NSDictionary,
并读取键值
,如:
In JSON parse, save the parsing data into NSDictionary,And read the key-value
like:
NSString *verCode = [JSONDict objectForKey:@"v"];
但有时,键值是其他格式,程序会崩溃,所以我需要隐蔽stringValue;
像这样:
but sometime, the key-value is other format, the program will crash, so I need covert to stringValue;
like this:
NSString *verCode = [[JSONDict objectForKey:@"v"] stringValue];
如何在iOS程序中捕获异常?
推荐答案
您可以在代码周围使用@try {}来捕获异常。
You can use @try{ } around code to catch exceptions.
在你的虽然更好的方法是查看数组中对象的类型,然后根据需要使用正确的转换:
In your case though a better approach is to look at the types of the object in the array for a key and use the right conversion as needed:
id object = [myJSONDict objectForKey:@"theValue"];
NSString *finalVal = nil;
if ( [object isKindOfClass:[NSNumber class]] )
finalVal = [object stringValue]
else
finalVal = object;
这篇关于如何在iOS中捕获异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!