I am working on catching errors in my app, and I am looking into using NSError
. I am slightly confused about how to use it, and how to populate it.
www.un.org/Depts/DGACM/index_spanish.htm 某个人可以举例说明我如何使用<代码>。 NSError ?
I am working on catching errors in my app, and I am looking into using NSError
. I am slightly confused about how to use it, and how to populate it.
www.un.org/Depts/DGACM/index_spanish.htm 某个人可以举例说明我如何使用<代码>。 NSError ?
当然,我通常采取的方法是,在操作时间可以错出,而参考的是NSError
点。 如果这种方法确实有错的话,我可以把“NSError
的提及与错误数据联系起来,并将零从该方法中退回。
例:
- (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;
}
这样,我们就能够采用这样的方法。 a. 甚至连二人都检查错误物体,除非该方法返回零:
// 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.
我们得以查阅错误的<代码>地方化说明<>/代码>,因为我们设定了<编码>本土化说明/代码>的价值。
更多信息的最佳地点是。 页: 1 这确实是好的。
http://www.cimgf.com/2008/04/coa-tutorial-using-nserror-to-great-effect/“rel=” 科拉·伊斯梅尔·阿莱德。
I would like to add some more suggestions based on my most recent implementation. I ve looked at some code from Apple and I think my code behaves in much the same way.
上述职位已经解释了如何制造NSError物体并归还这些物体,因此我与这一部分赢得了双手。 我只是试图建议一种很好的方法,将错误(代码、电文)纳入你自己的手里。
我建议设立1名负责人,以概述贵领域的所有错误(即:评估、图书馆等)。 我的现任领导人希望:
<>strong>FSError.h
FOUNDATION_EXPORT NSString *const FSMyAppErrorDomain;
enum {
FSUserNotLoggedInError = 1000,
FSUserLogoutFailedError,
FSProfileParsingFailedError,
FSProfileBadLoginError,
FSFNIDParsingFailedError,
};
<>strong>FSError.m
#import "FSError.h"
NSString *const FSMyAppErrorDomain = @"com.felis.myapp";
现在,在将上述数值用于错误时, 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;
}
以上代码的标准 Apple生成错误信息(eror. localizedDescription
)将考虑如下:
<编码> Error territorial=com.felis.myapp Code=1002 “行动无法完成。 (com.felis.myapp, 1002.)
以上所述对于开发商已经非常有益,因为电文显示发生错误的领域和相应的错误代码。 终端用户将不包含什么错误代码1002<>>>/code>,但我们现在需要为每种代码执行某些冰层信息。
对于错误的信息,我们必须牢记地方化(即使我们不执行当地化的信息)。 我在目前的项目中采用了以下做法:
(1) 建立一个包含错误的<条码>文件。 硬盘档案易于当地使用。 档案可以看一看:
FSError.strings
"1000" = "User not logged in.";
"1001" = "Logout failed.";
"1002" = "Parser failed.";
"1003" = "Incorrect username or password.";
"1004" = "Failed to parse FNID."
2) 添加宏观手段,将惯用代码转换为地方错误信息。 我在我的Constants+Macros.h档案中使用了2个宏观。 我总是将这一档案列入固定标题()。 为方便起见,MyApp-Prefix.pch
。
<>Constants+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)
3) 现在很容易根据错误代码显示用户友好的错误信息。 例如:
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
message:FS_ERROR_LOCALIZED_DESCRIPTION(error.code)
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
Great answer Alex. One potential issue is the NULL dereference. Apple s reference on Creating and Returning NSError objects
...
[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;
...
www.un.org/Depts/DGACM/index_spanish.htm 目标-C
NSError *err = [NSError errorWithDomain:@"some_domain"
code:100
userInfo:@{
NSLocalizedDescriptionKey:@"Something went wrong"
}];
<>Swift 3
let error = NSError(domain: "some_domain",
code: 100,
userInfo: [NSLocalizedDescriptionKey: "Something went wrong"])
请参看。
i 希望能对你有所帮助,但您必须阅读以下文件:http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/Reference/Reference.html。
我尝试总结一下Alex和jlmendezbonini要点的伟大答案,并添加一项修改,使ARC的所有内容都一致(远非因为ARC会抱怨,因为你应当返回<条码>id,这意味着“任何物体”,但BOOL
不是物体类型)。
- (BOOL) 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
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 NO;
}
// wohoo! We fed the world s children. The world is now in lots of debt. But who cares?
return YES;
}
现在,我们不核对我们方法电话的回报价值,而是检查<代码>err是否仍为nil
。 否则,我们就有一个问题。
// initialize NSError object
NSError* error = nil;
// try to feed the world
BOOL success = [self endWorldHunger:smallAmountsOfMonies error:&error];
if (!success) {
// inspect error
NSLog(@"%@", [error localizedDescription]);
}
// otherwise the world has been fed. Wow, your code must rock.
我所看到的另一个设计模式涉及使用区块,在使用方法时,这种区块特别有用。
我们有以下错误代码:
typedef NS_ENUM(NSInteger, MyErrorCodes) {
MyErrorCodesEmptyString = 500,
MyErrorCodesInvalidURL,
MyErrorCodesUnableToReachHost,
};
您将界定你可产生类似错误的方法:
- (void)getContentsOfURL:(NSString *)path success:(void(^)(NSString *html))success failure:(void(^)(NSError *error))failure {
if (path.length == 0) {
if (failure) {
failure([NSError errorWithDomain:@"com.example" code:MyErrorCodesEmptyString userInfo:nil]);
}
return;
}
NSString *htmlContents = @"";
// Exercise for the reader: get the contents at that URL or raise another error.
if (success) {
success(htmlContents);
}
}
那么,当你打电话时,你就不必担心宣布NSError物体(完成编码会给你),或检查返回价值。 你们只能提供两块:一是例外,一是例外,一是当它成功时,就会有人要求:
[self getContentsOfURL:@"http://google.com" success:^(NSString *html) {
NSLog(@"Contents: %@", html);
} failure:^(NSError *error) {
NSLog(@"Failed to get contents: %@", error);
if (error.code == MyErrorCodesEmptyString) { // make sure to check the domain too
NSLog(@"You must provide a non-empty string");
}
}];
extension NSError {
static func defaultError() -> NSError {
return NSError(domain: "com.app.error.domain", code: 0, userInfo: [NSLocalizedDescriptionKey: "Something went wrong."])
}
}
当我没有有效的错误反对时,我可以使用<代码>NSError.defaultError(。
let error = NSError.defaultError()
print(error.localizedDescription) //Something went wrong.
Well it s a little bit out of question scope but in case you don t have an option for NSError you can always display the Low level error:
NSLog(@"Error = %@ ",[NSString stringWithUTF8String:strerror(errno)]);
For a basic app with nonconsumable in-app purchases, has anyone figured out best practices for using SKPaymentQueue s restoreCompletedTransactions? Observations I know it s recommended to always ...
I am trying to list the contents of Ringtones directory in a TableView, however, I am only getting the last file in the directory in ALL cells, instead of file per cell. This is my code: - (...
I have a UITextField that is a subview of a UITableViewCell. When my view loads, I want the text field to become first responder. I have a pointer to the text field in the table cell, so to do this I ...
I ve been working on adding in-app purchases and was able to create and test in-app purchases using Store Kit (yay!). During testing, I exercised my app in a way which caused the app to crash mid ...
In my app i have a bunch of data i store in the NSUserdefaults. This information consists of an NSObject (Object1) with NSStrings and NSNumbers and also 2 instances of yet another object (Object2). ...
Basically I m downloading images off of a webserver and then caching them to the disk, but before I do so I want to mask them. I m using the masking code everyone seems to point at which can be found ...
I m using this code to resize an image on the iPhone: CGRect screenRect = CGRectMake(0, 0, 320.0, 480.0); UIGraphicsBeginImageContext(screenRect.size); [value drawInRect:screenRect blendMode:...
Is there a simple way of allowing interaction with a button in a UIView that lies under another UIView - where there are no actual objects from the top UIView on top of the button? For instance, ...