我创建了一个返回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,则会出现不兼容的指针类型错误。
此外,一旦我将方法返回YES,我该如何调用此方法并根据结果执行某些操作。 例如,我需要调用此方法,如果它是真的,那么做一些其他事情,如果不做任何事情......
答案 0 :(得分:3)
我不确定你在问什么,所以这里有一个猜测:你希望你的块返回一个值checkIfGameAlreadyExistsAgainst
。
当构造一个块时,它通常会生成从其环境引用的任何值的副本。如果您希望块在其环境中修改变量,则必须使用__block
标记该变量。在您的代码中,这看起来像:
__block BOOL blockStatus = YES;
[currentUserIsUser1 findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error)
{
...
blockStatus = NO;
}
];
if (!blockStatus)
{
...
}
重要提示:您正在呼叫的方法的名称findObjectsInBackgroundWithBlock
表示该块可能未被同步调用 ,这意味着该呼叫可能会返回在块执行之前。如果是这种情况,您需要以不同的方式解决问题;这可能涉及调用同步等效的findObjectsInBackgroundWithBlock
或修改checkIfGameAlreadyExistsAgainst
,以便它接受一个与其结果异步调用的块,而不是直接返回一个值。
HTH