0

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

我从一个视图控制器调用游戏模型中的方法,一旦创建了游戏,我需要对我的视图控制器进行回调,说明它是成功的,并且可以推送一个新的 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];

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

4

2 回答 2

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!
}];

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

于 2013-07-03T20:29:46.580 回答
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);
}
于 2013-07-03T20:25:12.707 回答