如何在我的iPhone应用程序中使用NSError?

Nic*_*ard 226 iphone objective-c nserror ios4 ios

我正在努力捕获我的应用程序中的错误,我正在研究使用NSError.我对如何使用它以及如何填充它感到有些困惑.

有人可以提供一个关于我如何填充然后使用的例子NSError吗?

Ale*_*lex 470

好吧,我通常做的是让我的方法可以在运行时错误输出引用NSError指针.如果某个方法确实在该方法中出错,我可以NSError使用错误数据填充引用并从方法返回nil.

例:

- (id) endWorldHunger:(id)largeAmountsOfMonies error:(NSError**)error {
    // begin feeding the world's children...
    // it's all going well until....
    if (ohNoImOutOfMonies) {
        // sad, we can't solve world hunger, but we can let people know what went wrong!
        // init dictionary to be used to populate error object
        NSMutableDictionary* details = [NSMutableDictionary dictionary];
        [details setValue:@"ran out of money" forKey:NSLocalizedDescriptionKey];
        // populate the error object with the details
        *error = [NSError errorWithDomain:@"world" code:200 userInfo:details];
        // we couldn't feed the world's children...return nil..sniffle...sniffle
        return nil;
    }
    // wohoo! We fed the world's children. The world is now in lots of debt. But who cares? 
    return YES;
}
Run Code Online (Sandbox Code Playgroud)

然后我们可以使用这样的方法.除非方法返回nil,否则甚至不用费心去检查错误对象:

// initialize NSError object
NSError* error = nil;
// try to feed the world
id yayOrNay = [self endWorldHunger:smallAmountsOfMonies error:&error];
if (!yayOrNay) {
   // inspect error
   NSLog(@"%@", [error localizedDescription]);
}
// otherwise the world has been fed. Wow, your code must rock.
Run Code Online (Sandbox Code Playgroud)

我们能够访问错误,localizedDescription因为我们设置了一个值NSLocalizedDescriptionKey.

获取更多信息的最佳位置是Apple的文档.这真的很棒.

关于Cocoa Is My Girlfriend还有一个很好的简单教程.

  • 这是有史以来最有趣的例子 (35认同)
  • -1:你真的需要合并验证`**error`的代码不是nil.否则,程序将抛出一个完全不友好的错误,并且不会显示正在发生的事情. (7认同)
  • @TomJowett如果我们最终无法仅仅因为Apple推动我们转向新的ARC世界,那么我真的很生气. (6认同)

Wol*_*urs 54

我想根据我最近的实施添加更多建议.我查看了Apple的一些代码,我认为我的代码行为方式大致相同.

上面的帖子已经解释了如何创建NSError对象并返回它们,所以我不打扰那部分.我将尝试建议一种在您自己的应用程序中集成错误(代码,消息)的好方法.


我建议创建1个标题,它将概述您域中的所有错误(即应用程序,库等).我当前的标题如下所示:

FSError.h

FOUNDATION_EXPORT NSString *const FSMyAppErrorDomain;

enum {
    FSUserNotLoggedInError = 1000,
    FSUserLogoutFailedError,
    FSProfileParsingFailedError,
    FSProfileBadLoginError,
    FSFNIDParsingFailedError,
};
Run Code Online (Sandbox Code Playgroud)

FSError.m

#import "FSError.h" 

NSString *const FSMyAppErrorDomain = @"com.felis.myapp";
Run Code Online (Sandbox Code Playgroud)

现在,当使用上述值进行错误时,Apple将为您的应用创建一些基本的标准错误消息.可能会创建一个错误,如下所示:

+ (FSProfileInfo *)profileInfoWithData:(NSData *)data error:(NSError **)error
{
    FSProfileInfo *profileInfo = [[FSProfileInfo alloc] init];
    if (profileInfo)
    {
        /* ... lots of parsing code here ... */

        if (profileInfo.username == nil)
        {
            *error = [NSError errorWithDomain:FSMyAppErrorDomain code:FSProfileParsingFailedError userInfo:nil];            
            return nil;
        }
    }
    return profileInfo;
}
Run Code Online (Sandbox Code Playgroud)

error.localizedDescription上述代码的标准Apple生成的错误消息()如下所示:

Error Domain=com.felis.myapp Code=1002 "The operation couldn’t be completed. (com.felis.myapp error 1002.)"

以上内容对于开发人员来说已经非常有用,因为该消息显示了发生错误的域以及相应的错误代码.最终用户将不知道错误代码的1002含义,所以现在我们需要为每个代码实现一些好消息.

对于错误消息,我们必须牢记本地化(即使我们没有立即实现本地化消息).我在当前项目中使用了以下方法:


1)创建一个strings包含错误的文件.字符串文件很容易本地化.该文件可能如下所示:

FSError.strings

"1000" = "User not logged in.";
"1001" = "Logout failed.";
"1002" = "Parser failed.";
"1003" = "Incorrect username or password.";
"1004" = "Failed to parse FNID."
Run Code Online (Sandbox Code Playgroud)

2)添加宏以将整数代码转换为本地化的错误消息.我在Constants + Macros.h文件中使用了2个宏.MyApp-Prefix.pch为方便起见,我总是在前缀header()中包含此文件.

常量+ Macros.h

// error handling ...

#define FS_ERROR_KEY(code)                    [NSString stringWithFormat:@"%d", code]
#define FS_ERROR_LOCALIZED_DESCRIPTION(code)  NSLocalizedStringFromTable(FS_ERROR_KEY(code), @"FSError", nil)
Run Code Online (Sandbox Code Playgroud)

3)现在很容易根据错误代码显示用户友好的错误消息.一个例子:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" 
            message:FS_ERROR_LOCALIZED_DESCRIPTION(error.code) 
            delegate:nil 
            cancelButtonTitle:@"OK" 
            otherButtonTitles:nil];
[alert show];
Run Code Online (Sandbox Code Playgroud)

  • 很棒的答案!但是为什么不将本地化描述放在它所属的用户信息字典中呢?[NSError errorWithDomain:FSMyAppErrorDomain code:FSProfileParsingFailedError userInfo:@ {NSLocalizedDescriptionKey:FS_ERROR_LOCALIZED_DESCRIPTION(error.code)}]; (9认同)

jlm*_*ini 37

Alex答案很棒.一个潜在的问题是NULL解除引用.Apple关于创建和返回NSError对象的参考

...
[details setValue:@"ran out of money" forKey:NSLocalizedDescriptionKey];

if (error != NULL) {
    // populate the error object with the details
    *error = [NSError errorWithDomain:@"world" code:200 userInfo:details];
}
// we couldn't feed the world's children...return nil..sniffle...sniffle
return nil;
...
Run Code Online (Sandbox Code Playgroud)


AlB*_*ebe 28

Objective-C的

NSError *err = [NSError errorWithDomain:@"some_domain"
                                   code:100
                               userInfo:@{
                                           NSLocalizedDescriptionKey:@"Something went wrong"
                               }];
Run Code Online (Sandbox Code Playgroud)

斯威夫特3

let error = NSError(domain: "some_domain",
                      code: 100,
                  userInfo: [NSLocalizedDescriptionKey: "Something went wrong"])
Run Code Online (Sandbox Code Playgroud)


Tir*_*rth 9

请参考以下教程

我希望它对你有所帮助,但在此之前你必须阅读NSError的文档

这是我最近发现的非常有趣的链接ErrorHandling