定义一个采用回调块的方法

时间:2013-07-03 20:14:04

标签: objective-c cocoa-touch callback objective-c-blocks

我已阅读Apple documentation on Blocks,但我不太确定如何在我的情况下使用它们。在我的应用程序中,我有一个游戏模型。这有一种创建两个用户游戏的方法。

从视图控制器中我调用游戏模型中的方法,一旦创建游戏,我需要回调我的视图控制器,说它成功了,可以推送新的VC。

当前代码

游戏模型

+(void)createNewGameAgainst:(PFUser *)user2 {
    NSLog(@"createNewGameAgainst");
    // First we put a HUD up for the user on the window
    MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithWindow:[UIApplication sharedApplication].keyWindow];
    [[UIApplication sharedApplication].keyWindow addSubview:HUD];
    HUD.labelText = NSLocalizedString(@"HUDCreateNewGame", @"HUD - Create New Game text");
    HUD.removeFromSuperViewOnHide = YES;

    [HUD showAnimated:YES whileExecutingBlock:^{
        // Do something

        PFObject *newGame = [PFObject objectWithClassName:@"Game"];
        [newGame setObject:[PFUser currentUser] forKey:kMESGameUser1];
        [newGame setObject:user2 forKey:kMESGameUser2];
        [newGame saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (succeeded) {
                NSLog(@"succeeded game creation");
            }
        }];

    }];

    NSLog(@"end of createNewGameAgainst");
}

查看控制器调用

[MESGameModel createNewGameAgainst:self.gameNewOpponentuser];

我需要知道如何更新上面的方法以获得回调块。然后更新视图控制器调用方法,以便在创建成功时执行/推送新的视图控制器。

2 个答案:

答案 0 :(得分:3)

你基本上可以这样做:

部首:

+(void)createNewGameAgainst:(PFUser *)user2 withCompletion:(void (^)(BOOL success))completionHandler;

实现:

+(void)createNewGameAgainst:(PFUser *)user2 withCompletion:(void (^)(BOOL success))completionHandler{
NSLog(@"createNewGameAgainst");
// First we put a HUD up for the user on the window
MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithWindow:[UIApplication sharedApplication].keyWindow];
[[UIApplication sharedApplication].keyWindow addSubview:HUD];
HUD.labelText = NSLocalizedString(@"HUDCreateNewGame", @"HUD - Create New Game text");
HUD.removeFromSuperViewOnHide = YES;

[HUD showAnimated:YES whileExecutingBlock:^{
    // Do something

    PFObject *newGame = [PFObject objectWithClassName:@"Game"];
    [newGame setObject:[PFUser currentUser] forKey:kMESGameUser1];
    [newGame setObject:user2 forKey:kMESGameUser2];
    [newGame saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            NSLog(@"succeeded game creation");
        }
        completionHandler(succeeded);
    }];

}];

NSLog(@"end of createNewGameAgainst");
}

完成状态更新后,您可以使用状态调用完成处理程序。

[MESGameModel createNewGameAgainst:self.gameNewOpponentuser withCompletion:^(BOOL success) {
if(success)
    //Do something wonderful
else
    //Ohs nos!
}];

调用完成处理程序后,您可以检查操作是否成功完成。

答案 1 :(得分:0)

我不太确定,如果我完全理解你的问题,但也许这样的事情会起作用:

+(void)createNewGameAgainst:(PFUser *)user2 callback:(void (^)(NSError *error))callback {
    // do something
    NSError *error = nil; // set to something useful if an error occurs
    callback(error);
}