在编写代码时,有许多情况必须视为运行时错误:alloc/init返回nil,未找到资源,[someClass canDoThis]对于绝对需要的功能返回NO,其中YES是自然答案, ...
对于所有这些情况,我都编写了一个exitWithMessage
例程(显示一个警告框),每个类都有一个kill
方法来释放分配的内存。
所以...在init
方法中,您遇到了这类异常,我想您可以这样做:
[self kill];
[OneClass exitWithFatalErrorMessage];
return nil;
- (void) exitWithFatalErrorMessage:(NSString*)message
{
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:NSLocalizedStringFromTable(@"Error" @"ErrorMessages", @"") message:message delegate:self cancelButtonTitle:NSLocalizedStringFromTable(@"Understood", @"ErrorMessages", @"") otherButtonTitles: nil];
[alert show];
[alert release];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
// stop the normal running of the app, there is a situation that would prevent it
}
- (void)kill
{
self.member = nil;
self.member2 = nil;
...
}
但这不起作用...我的警报没有显示(在init方法以外的其他地方使用exitWithMessage都可以正常工作。
您将如何处理这些案件?这一段编码是一种好方法吗?
如果是,为什么我的警报不显示(我进入示例的 View Controller initWithCoder方法)?
最佳答案
您是否真的在调用exitWithFatalErrorMessage方法,因为在您的代码中您调用exitWithMessage,请尝试将其更改为:
[OneClass exitWithFatalErrorMessage:@"Message"];
关于iphone - iPhone-如何在运行时处理错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9169051/