我花了很多时间来解决为什么当我的 View Controller 从堆栈中弹出时没有释放内存。这是我正在使用的悬崖笔记版本:
- (IBAction)submitTurn:(UIButton *)sender {
...
[imageFile saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error){
if (!error){
...
[game saveEventually];
...
[push sendPushInBackground];
}
}
else{
NSLog(@"Error submitting turn: %@ %@", error, [error userInfo]);
[[[UIAlertView alloc] initWithTitle:@"Error Saving Game" message:@"Try again later." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil] show];
}
} progressBlock:nil];
[self.navigationController popToRootViewControllerAnimated:YES];
}
当我运行我的应用程序并不断返回此 View Controller 并提交我的回合时,instruments/leaks 显示我有此 View Controller 的多个实时实例。然而,当我注释掉所有图像/游戏/推送保存并只是弹出 View 时,内存就会被释放,并且我永远不会有超过一个事件实例。
我也尝试过这样做,以确保在 poppingToRoot 之前所有内容都已保存并完成。
- (IBAction)submitTurn:(UIButton *)sender {
...
[imageFile saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error){
if (!error){
...
[game saveEventually:^(BOOL succeeded, NSError *error) {
...
[push sendPushInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
[self.navigationController popToRootViewControllerAnimated:YES];
}];
}
}];
}
else{
...
}
} progressBlock:nil];
}
仍然没有骰子。 如何弹回到根目录而不留下痕迹?
最佳答案
访问 self
时,您可能有一个由 block 创建的保留周期。
试试这个:
__unsafe_unretained YourClass* self_ptr = self;
在进入 block 之前,以及在 block 内使用self_ptr
而不是self
。
关于ios popToRoot 在使用 block 时不释放内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14060892/