开发者

Passing Error Delegates Around

I'm trying to incorporate some sort of error handling into an iOS app. After reading that try/catch blocks aren't really good practice, I'm now looking at the &error output parameter for NSURLConnection. I'm trying to pass in a reference to an NSError, then I keep passing it down through the chain.

The first function calls a method in my DAL:

NSError *error = nil;
SearchResult *res = [db getHereditaments:&error];
if (error) {
    [self performSelectorOnMainThread:@selector(DisplayError:) withObject:error waitUntilDone:NO];
    //todo: handle error
} else {
    [self performSelectorOnMainThread:@selector(DisplayResults:) withObject:res waitUntilDone:NO];
}

Then the second method (which is called) tries to pass down the error. This worked fine until I added the check for whether the NSError was nil, and data in this case is returned, so why is an error also returned?

The method called is:

    -(SearchResult *) getData:(NSError**)error {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *userName  = [prefs stringForKey:UsernameKey];
NSString * password =  [prefs stringForKey:PasswordKey];

NSURL *url = [UrlUtility getSearchResults:userName passwordHash:password];
CXMLDocument *开发者_StackOverflowresponseObj = [UrlUtility xmlDocWithUrl:url onError:&error];
if(error ==nil){// should be nil if the connection was successful shouldn't it?


Ok, first of all if you're passing the same error down the chain you need to pass &*error into the method.

Secondly if you deal with the error pointer at all you generally want to deal with *error rather than error.

And thirdly you should NEVER check if error == nil. You should be checking if responseObj == nil. If that is true then you can use the error, if not then you should not have an error.

Lastly, not completely related to the subject but should help you as a dev, you shouldn't really use "get" at the start of method names. Get is only ever used for returning various values by reference, which you should generally avoid. Your methods should probably be something like downloadSearchResultsWithError: and URLForSearchResultsWithUsername:password:

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜