当UIViewController解除分配时,如何在目标C中触发阻止事件。
例如:
[PGMemberObj requestWithUserName:@"ab" andPassword:@"cc" andCallback:^(BOOL isSuc){
if (isSuc) {
NSLog("Login Suc.");
}else
{
NSLog("Login Failed");
}
}];
当我弹出视图控制器并执行 dealloc 时,我仍然收到登录 Suc. 或登录失败消息。如何避免此问题?
尝试使用以下代码:
__weak UIViewController *weakSelf = self;
[PGMemberObj requestWithUserName:@"ab" andPassword:@"cc" andCallback:^(BOOL isSuc){
if ([weakSelf isViewLoaded] && [weakSelf.view window])
//The view controller still exists AND it's being shown on screen
else
//Either dealloc'd or not on screen anymore
}];
它将测试您的视图控制器是否仍然存在并且仍在屏幕上。只需检查weakSelf
,如果您不在乎它是否仍在屏幕上显示。
if (weakSelf)
//Still exists
else
//dealloc'd
如果我理解正确,如果您想在视图控制器不再活动时阻止块执行吗?这有点棘手,因为块被发送到你的PGMemberObj,所以你的视图控制器不再对块代码有任何控制。取消必须在执行区块的位置以PGMemberObj requestWithUserName
方法完成。也许你可以为视图控制器设置一个__block变量,并在触发回调之前检查它是否已被释放。
完成块通常是辅助线程。
你可以尝试这样的东西,
[PGMemberObj requestWithUserName:@"ab" andPassword:@"cc" andCallback:^(BOOL isSuc){
if (isSuc)
{
NSLog(@"Login Suc.");
[self.navigationController popViewControllerAnimated:YES];
}
else
{
NSLog(@"Login Failed");
UIAlertView *al=[[UIAlertView alloc]initWithTitle:@"Warning" message:@"Invalid username or password" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil];
[al show];
}
}];
我能想到的最佳解决方案是取消不再需要的身份验证。这意味着您的PGMemberObj
应包含将取消其身份验证过程的cancel
(或类似)方法。
另一种方法是将块重置为 nil
.在这种情况下,PGMemberObj
应具有一个成员对象来保存身份验证回调块,以及一个 copy
属性。
您可以调用 cancel
方法,或在 dealloc
方法中重置block
。
你可以尝试这样的东西:
__weak id *myWeakSelf = self;
[PGMemberObj requestWithUserName:@"ab" andPassword:@"cc" andCallback:^(BOOL isSuc) {
if (!myWeakSelf)
return;
if (isSuc) {
NSLog("Login Suc.");
}else
{
NSLog("Login Failed");
}
}];
使用 self 的weak
引用将允许检测块体在解除分配后何时执行self
。事实上,在这种情况下,myWeakSelf
被发现在块开始时nil
。
如果你想完全阻止块被调用,你需要设置一些机制,以便你的PGMemberObj
对象知道不应该再执行这个块。同样,在这种情况下,弱引用可能会有所帮助,您可以设置PGMemberObj
的weak
属性,以便在释放请求对象时将其为零(在这种情况下,您只能有一个未完成的请求)。