我不完全确定你想在那里做什么 - 你的回调是一个块......这是故意的吗?我希望您的方法看起来像这样:
- (void)signInAccountWithUserName:(NSString *)userName password:(NSString *)password;
如果您的回调的目的是在完成时执行一些额外的代码(在您调用方法时指定),那么块将很有用。例如,您的方法如下所示:
- (void)signInAccountWithUserName:(NSString *)userName
password:(NSString *)password
completion:(void (^)(void))completionBlock
{
// ...
// Log into the account with `userName` and `password`...
//
if (successful) {
completionBlock();
}
}
然后像这样调用方法:
[self signInAccountWithUserName:@"Bob"
password:@"BobsPassword"
completion:^{
[self displayBalance]; // For example...
}];
此方法调用会将用户登录到帐户,然后在完成后立即显示余额。这显然是一个人为的例子,但希望你能明白。
如果这不是您想要的,那么只需使用上述方法签名即可。
编辑(使用successful 变量的更好示例):
更好的设计是在完成块中传递一个布尔值,用于描述登录的情况:
- (void)signInAccountWithUserName:(NSString *)userName
password:(NSString *)password
completion:(void (^)(BOOL success))completionBlock
{
// Log into the account with `userName` and `password`...
// BOOL loginSuccessful = [LoginManager contrivedLoginMethod];
// Notice that we are passing a BOOL back to the completion block.
if (completionBlock != nil) completionBlock(loginSuccessful);
}
您还会看到,这一次我们在调用 completionBlock 参数之前检查它是否不是 nil - 如果您希望允许在不使用该方法的情况下使用该方法,这一点很重要 em> 一个完成块。你可以像这样使用这个方法:
[self signInAccountWithUserName:@"Bob"
password:@"BobsPassword"
completion:^(BOOL success) {
if (success) {
[self displayBalance];
} else {
// Could not log in. Display alert to user.
}
}];
更好的是(如果您可以原谅大量示例!),如果用户知道失败的原因对用户有用,请返回 NSError 对象:
- (void)signInAccountWithUserName:(NSString *)userName
password:(NSString *)password
completion:(void (^)(NSError *error))completionBlock
{
// Attempt to log into the account with `userName` and `password`...
if (loginSuccessful) {
// Login went ok. Call the completion block with no error object.
if (completionBlock != nil) completionBlock(nil);
} else {
// Create an error object. (N.B. `userInfo` can contain lots of handy
// things! Check out the NSError Class Reference for details...)
NSInteger errorCode;
if (passwordIncorrect) {
errorCode = kPasswordIncorrectErrorCode;
} else {
errorCode = kUnknownErrorCode;
}
NSError *error = [NSError errorWithDomain:MyLoginErrorDomain code:errorCode userInfo:nil];
if (completionBlock != nil) completionBlock(error);
}
}
然后调用者可以使用完成块中的NSError 来决定如何继续(很可能是向用户描述出了什么问题)。这种模式不太常见(尽管完全有效);大多数NSErrors 是通过指针间接返回的,例如在NSFileWrappers -initWithURL:options:error: 方法中:
NSError *error;
NSFileWrapper *fw = [[NSFileWrapper alloc] initWithURL:url options:0 error:&error];
// After the above method has been called, `error` is either `nil` (if all went well),
// or non-`nil` (if something went wrong).
然而,在登录示例中,我们可能预计登录尝试需要一些时间才能完成(例如登录到在线帐户),因此使用传递一个完成处理程序是完全合理的错误返回。