美文网首页
takeUnretainedValue与takeRetained

takeUnretainedValue与takeRetained

作者: ksnowlv | 来源:发表于2018-06-29 15:54 被阅读213次

    swift中,如果我们使用perform相关函数时,例如

     if let object = connectionItem.perform(connectionSEL, with: nil) {
                        (object as! YKURLConnection).cancel()
     }
    

    此时会报警告

     Cast from 'Unmanaged<AnyObject>' to unrelated type 'YKURLConnection' always fails
    

    虽然代码可以正常运行,报这种警告,也是让人心理很不爽。

    如何解决呢?使用Unmanaged<anyobject>的takeUnretainedValue()即可解决。

    查了下文档

    1.takeUnretainedValue

    Gets the value of this unmanaged reference as a managed reference without consuming an unbalanced retain of it. This is useful when a function returns an unmanaged reference and you know that you’re not responsible for releasing the result. Returns The object referenced by this Unmanaged instance.

    2.takeRetainedValue

    Gets the value of this unmanaged reference as a managed reference and consumes an unbalanced retain of it. This is useful when a function returns an unmanaged reference and you know that you’re responsible for releasing the result. Returns The object referenced by this Unmanaged instance.

    3.区别

    • takeUnretainedValue不需要负责对象的释放。
    • takeRetainedValue需要调用者负责对象的释放,通常是一些copy/create产生的对象,

    也可看下stackoverflow上一些解释

    相关文章

      网友评论

          本文标题:takeUnretainedValue与takeRetained

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