我有一个奇怪的崩溃,发生了大麦,我想知道是否可能是由于腐败的数据被读取?我发生了这个错误:
-[NSKeyedUnarchiver initForReadingWithData:]: incomprehensible archive
> # Binary Image Name Address Symbol 0 CoreFoundation 0x3357b2a3 __exceptionPreprocess
> 1 libobjc.A.dylib 0x3b3df97f objc_exception_throw
> 2 CoreFoundation 0x3357b1c5 -[NSException initWithCoder:]
> 3 Foundation 0x33e124ef -[NSKeyedUnarchiver initForReadingWithData:]
> 4 Foundation 0x33e73537 +[NSKeyedUnarchiver unarchiveObjectWithFile:]
我的代码很好,这在我的应用程序中发生了一次,但我只是想知道损坏的数据是否是发生这种情况的可行原因。如果是这样有办法处理腐败数据?
答案 0 :(得分:4)
您可以将部分代码包装在@try @catch构造中以评估异常并避免崩溃。 这是一个例子:
- (UIImage*) loadImageFromCacheWithFilePath: (NSString*) somePath {
UIImage* image = nil;
@try {
image = [NSKeyedUnarchiver unarchiveObjectWithFile:somePath];
} @catch (NSException* exception) {
// Surpress any unarchiving exceptions and continue with nil
NSLog(@"Load image from cache was failed with exception: %@", [exception reason]);
}
return image; //This will return nil if exception caught
}
答案 1 :(得分:3)
以下是一些示例代码:
NSError * serializationError = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&serializationError];
if(serializationError == nil && jsonArray != nil) {
NSLog(@"%@", jsonArray);
}