I have a callback method that I got to work, but I want to know how to pass values to it.
What I have is this:
@interface DataAccessor : NSObject
{
void (^_completionHandler)(Account *someParameter);
}
- (void) signInAccount:(void(^)(Account *))handler;
The code above works, but I want to pass values to the method. How would this look? Something like:
- (void) signInAccount:(void(^)(Account *))handler user:(NSString *) userName pass:(NSString *) passWord;
?
I'm not entirely sure what you're trying to do there - your callback is a block... is that intentional? I would expect your method to look something like this:
If the intention of your callback is to execute some additional code (specified when you call the method) on completion, then a block would be useful. For example, your method would look like this:
And then call the method like so:
This method call would log the user into the account and then as soon as that is complete, show the balance. This is clearly a contrived example, but hopefully you get the idea.
If this is not the kind of thing you intended, then simply use a method signature like the one above.
EDIT (A better example using the
successful
variable):A better design would be to pass a Boolean back in the completion block that describes how well the login went:
You'll also see that this time around we're checking that the
completionBlock
parameter is notnil
before calling it - this is important if you want to allow the method to be used without a completion block. You might use this method like so:Better still (if you can excuse the swaths of examples!), if it would be useful for the user to know the reason for the failure, return an
NSError
object:The caller can then make use of the
NSError
in the completion block to decide how to proceed (most likely, to describe to the user what went wrong). This kind of pattern is slightly less common (though perfectly valid); mostlyNSError
s are returned by pointer indirection, for example in theNSFileWrapper
s-initWithURL:options:error:
method:In the login example, however, we are probably expecting the login attempt to take some amount of time to complete (for example logging into an online account), so it is perfectly reasonable to make use of a completion handler that passes an error back.