-1

我创建了一个返回 BOOL 的新方法,如下所示。

+(BOOL)checkIfGameAlreadyExistsAgainst:(PFUser *)opponentUser {
    // Find all the games where the current user is user1 and the opponentUser is user2
    PFQuery *currentUserIsUser1 = [PFQuery queryWithClassName:@"Game"];
    [currentUserIsUser1 whereKey:kMESGameUser1 equalTo:[PFUser currentUser]];
    [currentUserIsUser1 whereKey:kMESGameUser2 equalTo:opponentUser];
    [currentUserIsUser1 whereKey:kMESGameIsActive equalTo:[NSNumber numberWithBool:YES]];
    [currentUserIsUser1 findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (objects) {
            // We have games where the current user is user1
            // NEED TO RETURN NO TO THIS METHOD AND NOT RUN FURTHER IN METHOD...
            NSLog(@"Results returned for existing game where current user is User1. Results: %@",objects);
        } else {
            // If there are no objects from first query and no error we run the second query
            if (!error) {
                // Find all the games where the current user is user2 and the opponentUser is user1
                PFQuery *currentUserIsUser2 = [PFQuery queryWithClassName:@"Game"];
                [currentUserIsUser2 whereKey:kMESGameUser1 equalTo:opponentUser];
                [currentUserIsUser2 whereKey:kMESGameUser2 equalTo:[PFUser currentUser]];
                [currentUserIsUser2 whereKey:kMESGameIsActive equalTo:[NSNumber numberWithBool:YES]];
                [currentUserIsUser2 findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
                    if (objects) {
                        // We have games where the current user is user2
                        // NEED TO RETURN NO TO THIS METHOD AND NOT RUN FURTHER IN METHOD...
                        NSLog(@"Results returned for existing game where current user is User2. Results: %@",objects);
                    }
                }];
            }
        }
    }];


    return NO;
}

我遇到的问题是如何在方法的块内返回一个 YES 值。请参阅方法中的部分 // NEED TO RETURN NO TO this METHOD AND NOT RUNFTHER IN METHOD... 我怎样才能在此处返回 YES。如果我添加 return YES,我会得到一个不兼容的指针类型错误。

除此之外,一旦我的方法返回 YES,我该如何调用这个方法并根据结果做一些事情。例如我需要调用这个方法,如果它是真的然后做别的事情,如果不是什么都不做......

4

1 回答 1

3

我不确定你在问什么,所以这里有一个猜测:你希望你的块返回一个值到checkIfGameAlreadyExistsAgainst.

当构建一个块时,它通常会复制从其环境引用的任何值。如果您希望您的块在其环境中修改变量,您必须用 标记该变量__block。在您的代码中,这看起来像:

__block BOOL blockStatus = YES;
[currentUserIsUser1 findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error)
 {
    ...
    blockStatus = NO;
 }
];

if (!blockStatus)
{
   ...
}

重要提示:您正在调用的方法的名称findObjectsInBackgroundWithBlock,表明该块可能不会被同步调用,这意味着调用可能会在该块执行之前返回。如果是这种情况,您需要以不同的方式解决问题;这可能涉及调用同步等价物findObjectsInBackgroundWithBlock或进行修改checkIfGameAlreadyExistsAgainst,以便它接受一个块,它用其结果异步调用该块,而不是直接返回一个值。

高温高压

于 2013-07-04T23:12:32.937 回答