tra*_*per 4 memory-management ios objective-c-blocks retain-cycle uialertcontroller
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"alert" message:nil preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action = [UIAlertAction actionWithTitle:@"action" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[self doSomething];
}];
[alert addAction:action];
[self presentViewController:alert animated:YES completion:nil];
Run Code Online (Sandbox Code Playgroud)
我理解这个循环.self保留UIAlertController,UIAlertController保留UIAlertAction,UIAlertAction保留self
我的意思是内部不能将这个类设计为在UIAlertActions运行之后释放所有内容吗?
-
为了澄清,我知道通过使用对自我的弱引用可以避免这个问题.
我要问的是,UIAlertController一旦用户选择了一个动作,为什么不会将所有动作(以及它们的处理程序块)都清零.这将打破周期,避免我们需要做的整个弱势舞蹈.
像这样......
@implementation UIAlertController
...
// An action button was pressed
- (void)actionSelectedIndex:(NSInteger)index
{
UIAlertAction *action = self.actions[index];
action.handler(action); // Run the action handler block
self.actions = nil; // Release all the actions
}
Run Code Online (Sandbox Code Playgroud)
Man*_*nny 12
这里的问题和答案令我感到困惑,这是我的搜索结果,所以我想直接记录:
示例中没有保留周期,因此在这种情况下不需要创建"弱自我".保留周期的唯一时间是自我是否具有强烈的警报参考.
UIAlertController被设计为在执行后释放所有内容,前提是您没有强有力的引用.
我在示例类中尝试了该示例,并且在控制器的pop上成功调用了dealloc.
通过例子总结:
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"alert" message:nil preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action = [UIAlertAction actionWithTitle:@"action" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//No retain cycle, no need for weak self
[self doSomething];
}];
[alert addAction:action];
[self presentViewController:alert animated:YES completion:nil];
Run Code Online (Sandbox Code Playgroud)
VS
//assume this is a strong reference
self.alert = [UIAlertController alertControllerWithTitle:@"alert" message:nil preferredStyle:UIAlertControllerStyleAlert];
__weak __typeof(self)weakSelf = self;
UIAlertAction *action = [UIAlertAction actionWithTitle:@"action" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//Need a weakSelf to avoid retain cycle
[weakSelf doSomething];
}];
[self.alert addAction:action];
[self presentViewController:self.alert animated:YES completion:nil];
Run Code Online (Sandbox Code Playgroud)
旁注:假设在将其放入块中时总是需要使用弱引用是错误的.