美文网首页
在closure中处理循环引用

在closure中处理循环引用

作者: 幸运的小强本人 | 来源:发表于2016-04-10 13:04 被阅读71次

Swift是一们安全的语言,对于Objective-C中经常出现的block引起的循环引用问题处理的更好,在closure中引用成员属性的时候,会强制使用self,否则编译不过。如下代码:

class TestClass {
    var name: String = "aa"
    func viewDidLoad() {
        testEmbededFunction { () -> () in
            name = "bb"
        }
    }

    func testEmbededFunction(f: ()->()) {
        f()
    }
 }

上面的代码会出现编译错误,提示信息如下:

error.png

苹果官方解释如下:

Swift requires you to write self.someProperty or self.someMethod() (rather than just someProperty or someMethod()) whenever you refer to a member of self within a closure. This helps you remember that it's possible to capture self by accident

是因为closure中capture了self,如果self再引用closure的话,就会导致循环引用。因此解决循环引用就有两种方式:
1、保证closure不会强引用self
2、保证self不会强引用closure

第一种情况的解决办法:
使用capture list来解决[weak self, unowned self]

第二种情况的解决办法,
在Swift中可以使用@noescape来保证这一点,比如这样定义方法就没事了:

func testEmbededFunction(@noescape f: ()->()) { 
  f() 
}

官方文档中对noescape的描述:

Apply this attribute to a function or method declaration to indicate that a parameter it will not be stored for later execution, such that it is guaranteed not to outlive the lifetime of the call. Function type parameters with the noescape declaration attribute do not require explicit of self. for properties or method

相关文章

  • 在closure中处理循环引用

    Swift是一们安全的语言,对于Objective-C中经常出现的block引起的循环引用问题处理的更好,在clo...

  • unowned 和 weak 的小事儿

    自从接触了swift 之后,Closure 算是用的最多的东西了,为了避免循环引用,一直喜欢在Closure里面 ...

  • iOS Swift 关于内存管理需要注意的地方

    1.为避免循环引用,在使用代理时声明为weak对象 2.使用closure闭包时注意不要形成循环引用 3.push...

  • Swift中closure的循环引用记录

    1、定义一个controller: TestController并添加如下代码 然后添加方法进行测试: 1 不会循...

  • swift - 闭包基础

    闭包 closure 闭包在Swift中应用广泛,在许多系统库方法中都能看到。 无名本质是函数使用时注意循环引用 ...

  • Swift闭包循环引用

    无论OC中的Block还是Swift中的闭包Closure,经常因为使用不当从而造成循环引用从而导致内存泄漏,如何...

  • 闭包

    在计算机科学中,闭包(Closure)是词法闭包(Lexical Closure)的简称,是引用了自由变量的函数。...

  • 闭包

    在计算机科学中,闭包(Closure)是词法闭包(Lexical Closure)的简称,是引用了自由变量的函数。...

  • NSTimer循环引用问题

    在实际的开发中,在需要定时器时,这样的代码很常见。 那么这样代码如果处理不当,很容易引起循环引用问题。 循环引用产...

  • 扒一扒swift中的unowned和weak上

    最近项目中踩到了Closure使用unowned和weak修饰self对象避免循环引用所带来的坑,之前不是太了解,...

网友评论

      本文标题:在closure中处理循环引用

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