How to catch exception in iOS?

风格不统一 提交于 2019-12-20 06:30:07

问题


In JSON parse, save the parsing data into NSDictionary, And read the key-value like:

NSString *verCode = [JSONDict objectForKey:@"v"];

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];

How can I catch exception in iOS program?


回答1:


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;


来源:https://stackoverflow.com/questions/8584687/how-to-catch-exception-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!