我想反映UIKit中了AppKit的錯誤處理機制,主要是因爲我想借此響應鏈的優勢,向上向前的錯誤。我沒有完全測試,但目前看起來像下面。
它反映的AppKit非常接近,但可以重寫will/did鉤子來分別執行自定義錯誤表示和恢復。默認行爲是顯示用於演示的UIAlertView並使用psuedo-NSErrorRecoveryAttempting對象進行恢復。
@implementation UIResponder (ErrorHandling)
- (void)presentError:(NSError *)error
completion:(void (^)(BOOL recovered))completion
{
if (nil == (error = [self willPresentError:error])) {
return;
}
if (self.nextResponder) {
[self.nextResponder presentError:error completion:completion];
return;
}
// Code to create and show UIAlertView
// e.g. https://github.com/jayway/CWUIKit/blob/master/Classes/UIAlertView%2BCWErrorHandler.m
// The UIAlertViewDelegate calls didPresentError...
}
/*
Override to customise the error object as in AppKit.
You can also perform your own error presentation, and return nil to terminate the default handling.
Custom error presentation UI should still call didPresentError... when dismissed
*/
- (NSError *)willPresentError:(NSError *)error
{
return error;
}
/*
Override to perform custom error recovery.
*/
- (void)didPresentError:(NSError *)error optionIndex:(NSInteger)optionIndex completion:(void (^)(BOOL recovered))completion
{
id recoveryAttempter = [error recoveryAttempter];
if ([recoveryAttempter respondsToSelector:@selector(attemptRecoveryFromError:optionIndex:completion:)]) {
[recoveryAttempter attemptRecoveryFromError:error optionIndex:optionIndex completion:completion];
}
}
@end
在某一時刻,我寫了一段代碼來完成這個工作(使用UIAlertView等提供NSError的句柄),但是我還沒有看到實際上有一個'recoveryAttempter'的錯誤,所以我不知道它是否正確。 – Anomie