美文网首页swiftiOS
[问答专栏] All func pointers need a

[问答专栏] All func pointers need a

作者: NinthDay | 来源:发表于2016-01-03 21:58 被阅读30次

文章题目:All func pointers need a protocol now
作者:pmst(1345614869)
微博:PPPPPPMST

正文

问题链接

问题描述

Gargoyle 想实现一个对象之间的回调,但是却未使用 protocol + delegate 的设计模式,而是使用了如下方法:

final class MyView: UIView {  
    var onSomeAction: ((String) -> Void)!  
}  
  
final class MyViewController: UIViewController {  
    let myView = MyView(frame: CGRectZero)  
    override func viewDidLoad() {  
        super.viewDidLoad()  
        myView.onSomeAction = someFunc  
    }  
  
    private func someFunc(str: String) {  
    }  
}  

注意到 myViewController 实例与 myView 实例会形成一个 retain cycle ,倘若你想为 var onSomeAction 使用 weak 关键字,抱歉!报错“weak cannot be applied to non-class type xxxx” ,显然对于非 class 对象你无法使用 weak 关键字。

问题解答

Jessy 提供了一种解决方案:

var onSomeAction_get: () -> (String -> Void)! = {nil} 

myView.onSomeAction_get = {[unowned self] in self.someFunc} 

首先对闭包类型进行了修改,从(String) -> Void 变为 () -> (String -> Void) ;其次为 myViewonSomeAction_get 赋值是用闭包方式,其中使用了[unowned self] 保证不会形成retain cycle,这也是问题解决的关键所在。

相关文章

  • [问答专栏] All func pointers need a

    文章题目:All func pointers need a protocol now作者:pmst(1345614...

  • 2020-08-25 详解Transformer

    知乎专栏微信文章简书《Attention is All You Need》浅读

  • 《普通心理学》+英语

    all too soon ,过早 All to soon ,the garden will need to be ...

  • I need to change

    I need to change?but how to . we all need to change,may n...

  • Need Change

    We all need to change. ...

  • 装饰器demo

    def all_a(func):def spl(file_name):data = func(file_name)...

  • All I Need

    刚刚熬夜追完《吸血鬼日记》的最终季,已经记不得是从哪一年开始追,只记得当时是每周更,一更新就立马看,后来因为各种原...

  • All I need

    同学们好!还记得20年前,刚刚高考完后的我们的样子么?那个唯一没有任何负担的暑假,我们都如何度过的,还记得么?20...

  • CNN Is All You Need 论文解析

    CNN Is All You Need 论文解析

  • He

    Need or not ---all for a broken heart Please open...

网友评论

    本文标题:[问答专栏] All func pointers need a

    本文链接:https://www.haomeiwen.com/subject/parohttx.html