简体   繁体   English

iPhone-如何在运行时处理错误

[英]iPhone - How to handle errors at runtime

When writing code, there are many situations that must be treated as runtime errors : an alloc/init returns nil, a resource is not found, a [someClass canDoThis] returns NO for an absolutely-needed feature where YES would be the natural answer, ... 编写代码时,有许多情况必须视为运行时错误:alloc / init返回nil,找不到资源,[someClass canDoThis]返回绝对必需功能的NO,其中YES是自然答案, ...

For all these situations, I have written an exitWithMessage routine (that displays an alert box), and each class has a kill method that frees allocated memory. 对于所有这些情况,我都编写了exitWithMessage例程(显示警告框),并且每个类都有一个kill方法来释放分配的内存。

So... When in an init method, you have these kind of exceptions, I supposed you could do : 所以...当使用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;
    ...
}

But this does not work... My alert is not displayed (the exitWithMessage works fine when used anywhere else than into an init method. 但这不起作用...我的警报没有显示(在init方法以外的其他地方使用exitWithMessage都可以正常工作。

How would you handle those cases ? 您将如何处理这些案件? Is this piece of coding a fine way to do ? 这一段编码是一种好方法吗?
If yes, why does my alert do not display (I'm into a view controller initWithCoder method for the example) ? 如果是,为什么我的警报不显示(我进入示例的视图控制器initWithCoder方法)?

您实际上是否在调用exitWithFatalErrorMessage方法,因为在您的代码中您改为调用exitWithMessage,请尝试将其更改为:

[OneClass exitWithFatalErrorMessage:@"Message"];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM