我有一个块,我从firebase检查用户的状态属性。如果status属性为“free”,我想从块中返回,否则我想搜索其他用户并检查其状态,直到找到“free”用户为止:
void( ^ myResponseBlock)(BOOL finished) = ^ void(BOOL finished) {
if (finished) {
if ([self.freedom isEqualToString: @"free"]) {
NSLog(@"free!");
return;
} else if ([self.freedom isEqualToString: @"matched"]) {
NSLog(@"get another user");
//get another user
do {
//picking another random user from array
rando = arc4random_uniform(arraycount);
}
while (rando == randomIndex && rando == [self.randString intValue]);
self.randString = [NSString stringWithFormat: @"%u", rando];
[users removeAllObjects];
[users addObject:usersArray[rando]];
self.freeUser = users.firstObject;
NSLog(@"set up another check");
//error is called after this block is called here, again
[self checkIfFree: myResponseBlock];
} else {
NSLog(@"error!");
}
} else {
NSLog(@"not finished the checking yet");
}
};
[self checkIfFree: myResponseBlock];
如图所示,当在下面的'compblock(YES)'行上第二次调用块时,我收到'BAD ACCESS'错误:
-(void)checkIfFree:(myCompletion) compblock{
self.freeUserFB = [[Firebase alloc] initWithUrl:[NSString stringWithFormat: @"https://skipchat.firebaseio.com/users/%@", self.freeUser.objectId]];
[self.freeUserFB observeEventType:FEventTypeValue withBlock:^(FDataSnapshot *snapshot)
{
self.otherStatus = snapshot.value[@"status"];
NSLog(@"snapshot info %@", snapshot.value);
if ([self.otherStatus isEqualToString:@"free"]) {
self.userIsFree = YES;
self.freedom = @"free";
NSLog(@"user is free in the check method %@", self.freedom);
}
else{
self.userIsFree = NO;
self.freedom = @"matched";
NSLog(@"user is matched in the check method %@", self.freedom);
}
compblock(YES);
}];
}
如果不必调用块并且已检查的第一个用户已经“空闲”,则一切正常。我被困在为什么我得到这个错误/崩溃,并想知道如何解决它!
谢谢!
答案 0 :(得分:2)
block
捕获传入的所有变量,包括它自身,但是变量myResponseBlock
尚未在块内初始化。因此,您使用checkIfFree
值调用nil
方法,从而导致应用崩溃。
您可以做的一件事就是将您的阻止声明为__block
变量。
__block __weak void(^weakResponseBlock)(BOOL);
void(^myResponseBlock)(BOOL);
weakResponseBlock = myResponseBlock = ^void(BOOL finished) {
...
if (weakResponseBlock) {
[self checkIfFree:weakResponseBlock];
}
}
此外,请注意,块保留传递给它们的所有变量。在这种情况下,您将在块中保留 self ,因此只要块执行,它就永远不会被释放。因此,除非另有要求,否则始终将弱引用传递给块。
__weak UIViewController *weakSelf = self;
weakResponseBlock = myResponseBlock = ^void(BOOL finished) {
...
if (weakResponseBlock) {
[weakSelf checkIfFree:weakResponseBlock];
}
}
答案 1 :(得分:2)
我认为你可能还有一个错误,因为所有的块都是在堆栈上创建的。因此,如果发生任何异步,myResponseBlock将会消失。
我建议您将myResponse块复制(使用带有复制属性的属性)复制到属性中并从那里重复使用。这样你的块就会生存在堆上,当self被设置为nil时就会消失。