BOOL方法在块内部不返回YES

我创build了一个返回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值。 请参阅方法中的说明部分//必须不返回此方法并且不能在方法中继续运行…如何在此处返回YES。 如果我添加返回YES,我得到一个不兼容的指针types错误。

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

我不知道你在问什么,所以这是一个猜测:你希望你的块返回一个值checkIfGameAlreadyExistsAgainst

在构build块时,通常会从其环境引用任何值的副本 。 如果希望块在其环境中修改variables,则必须使用__block标记该variables。 在你的代码中,这看起来像这样:

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

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

HTH

    Interesting Posts