13

我在 iOS 上找不到正确使用NSErrorUIAlertView和的示例。NSErrorRecoveryAttempting我能找到的大多数文档和示例都涵盖了 OS X 上的等效功能,其中相关行为由 Cocoa 集成。但在 iOS 中,似乎有必要“手动”执行此操作,但我找不到如何完成的好例子。

我非常感谢一些使用 NSError 中的信息来支持从NSErrors报告给用户的恢复尝试的最佳实践示例。

4

3 回答 3

6

根据苹果的文档:

重要提示: NSError 类在 Mac OS X 和 iOS 上都可用。但是,错误响应和错误恢复 API 和机制仅在 Application Kit (Mac OS X) 中可用。

所以,我不确定你是否可以使用NSErrorRecoveryAttempting它,即使它似乎在文档中定义(看起来这是 UIKit 文档的一个区域,在从 AppKit 的文档复制后尚未更新)。

以下是我如何处理代码中的错误:

NSError *error = nil;
id result = [SomeClass doSomething:&error];

if (!result) {
    NSLog(@"Do something failed: %@", error);
    UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Something failed!" message:@"There was an error doing something." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
    [alert show];
    return;
}
于 2011-05-18T09:13:27.090 回答
2

我发现了一个很好的例子。

请参阅 James Beith 的以下博客文章和 GitHub 代码(包括示例项目)

http://www.realmacsoftware.com/blog/cocoa-error-handling-and-recovery

https://github.com/realmacsoftware/RMErrorRecoveryAttempter

我能够在 iPhone 模拟器上成功使用它。

于 2013-03-07T17:27:22.107 回答
1

我试图在 UIKit 中镜像 AppKit 的错误处理机制,主要是因为我想利用响应者链向上转发错误。我还没有完全测试过,但目前它看起来像下面这样。

它非常接近地反映了 AppKit,但是可以覆盖 will/did 挂钩以分别执行自定义错误呈现和恢复。默认行为是显示 UIAlertView 进行演示,并使用伪 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
于 2012-10-26T08:13:53.090 回答