将NSData
解析为字典时出现随机崩溃。我用下面的代码。
-(NSArray *)enumDataParser:(NSMutableData *)responseData
{
@try {
NSError *error;
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
}
@catch (NSException *exception) {
[[IFieldServiceCrashLog sharedLog] writeExceptionLogFile:exception];
[self performCatchOperation:exception];
}
}
有时我会收到“ nil”,有时我的应用程序崩溃(Exception not catched
)。
我确定responseData
不会为零,因为每当发生崩溃时,"error"
都不会给我一个原因(错误为零)。
应用程序在方法JSONObjectWithData
本身崩溃。我该如何解决这个问题或处理异常情况?
答案 0 :(得分:0)
仅JSON反序列化字典或数组,因此您可以检查并查看日志。 其他,请参阅选项类型:->枚举NSJSONReadingOptions,例如“ options:NSJSONReadingAllowFragments”
typedef enum NSJSONReadingOptions : NSUInteger {
NSJSONReadingMutableContainers = (1UL << 0),
NSJSONReadingMutableLeaves = (1UL << 1),
NSJSONReadingAllowFragments = (1UL << 2)
} NSJSONReadingOptions;
示例:
NSError *error = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error];
if (error != nil) {
NSLog(@"***** %@", error.localizedDescription);
} else if (jsonObject != nil) {
NSLog(@"*** JSON Data converted to NSObject!");
if ([jsonObject isKindOfClass:[NSDictionary class]]) {
NSDictionary *deserializedDictionary = (NSDictionary *)jsonObject;
NSLog(@"JSON Obj class: %@", NSStringFromClass([deserializedDictionary class]));
NSLog(@"*** its Dictionary Object from JSON Data: %@", deserializedDictionary.description);
} else if ([jsonObject isKindOfClass:[NSArray class]]) {
NSArray *deserializedArray = (NSArray *)jsonObject;
NSLog(@"JSON Obj class: %@", NSStringFromClass([deserializedArray class]));
NSLog(@"*** its Array Object from JSON Data: %@", deserializedArray.description);
} else {
NSLog(@"JSON Obj class: %@", NSStringFromClass([jsonObject class]));
NSLog(@"*** its UNKNOWN Object from JSON Data: %@", jsonObject);
}
}