takeUnretainedValue与takeRetained

2018-06-29  本文已影响213人  ksnowlv

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.区别

也可看下stackoverflow上一些解释

上一篇 下一篇

猜你喜欢

热点阅读