在RxSwift闭包上使用'self'...实例方法作为参数呢? [英] Using 'self' on RxSwift closures... What about instance methods as param?

查看:216
本文介绍了在RxSwift闭包上使用'self'...实例方法作为参数呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

其他堆栈溢出问题中,强调捕获[weak self]应该用于不属于该类的闭包,因为self在闭包完成之前可能为nil.当闭包由类本身拥有时的替代方法是[unowned self].

In other stack overflow questions, it was emphasized that the capture [weak self] should be used for closures that aren't owned by the class because self could be nil before the closure completes. An alternative when the closure is owned by the class itself is [unowned self].

我的问题是,当我作为参数传递的函数是当前类的实例方法时,我需要使用[unowned self]吗?

My question is do I need to use [unowned self] when the function I pass as a parameter is an instance method of the current class?

import RxSwift

class Person {
    var name = "Default name"

    class func getPersons() -> Observable<Person> {
        // ...
    }


}

class MyController: UIViewController {
    let disposeBag = DisposeBag()

    // I know this right
    func unownedDisplayPeople() {

        Person.getPersons()
            .subscribeNext { [unowned self ] person in
                self.displayName(person)
            }
            .addDisposableToBag(disposeBag)
    }

    // But what about this?
    func whatAboutThisDisplayPeople() {

        Person.getPersons()
            .subscribeNext(displayName)
            .addDisposableToBag(disposeBag)
    }

    // Or this?
    func orThisDisplayPeople() {

        Person.getPersons()
            .subscribeNext(self.displayName)
            .addDisposableToBag(disposeBag)
    }

    func displayName(person: Person) {
        print("Person name is \(person.name)")
    }
}

如果仅通过实例方法时仍需要考虑引用计数,该怎么办? [unowned self]放在哪里?还是我刚刚通过实例方法时就已经将它视为[unowned self]了?

If I still need to think about the reference counting when I just pass an instance method, how do I do it? Where do i put the [unowned self]? Or is it considered [unowned self] already when I just pass the instance method?

推荐答案

不幸的是,将实例方法传递给subscribeNext 保留self.为了更加通用,存储对实例方法的引用将增加实例的保留计数.

Unfortunately, passing an instance method to subscribeNext will retain self. To be more generic, storing a reference to an instance method will increase the retain count of the instance.

let instance = ReferenceType()
print(CFGetRetainCount(instance)) // 1

let methodReference = instance.method
print(CFGetRetainCount(instance)) // 2

这里唯一的解决方案是做您在unownedDisplayPeople中所做的事情.

The only solution here is do what you have done in unownedDisplayPeople.

let instance = ReferenceType()
print(CFGetRetainCount(instance)) // 1

let methodReference = { [unowned instance] in instance.method() }
print(CFGetRetainCount(instance)) // 1

这篇关于在RxSwift闭包上使用'self'...实例方法作为参数呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆