我正在努力捕捉我的应用程序中的错误,我正在考虑使用NSError
.我对如何使用它以及如何填充它有点困惑.
Could someone provide an example on how I populate then use 100?
我正在努力捕捉我的应用程序中的错误,我正在考虑使用NSError
.我对如何使用它以及如何填充它有点困惑.
Could someone provide an example on how I populate then use 100?
嗯,我通常做的是让我的方法引用一个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;
}
然后我们可以使用这样的方法.甚至不必判断错误对象,除非该方法返回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.
我们能够访问错误的localizedDescription
,因为我们将值设置为NSLocalizedDescriptionKey
.
获取更多信息的最佳地点是Apple's documentation.这真的很好.
还有一个关于Cocoa Is My Girlfriend的很好的、简单的教程.