简体   繁体   English

我何时/必须将ReactiveCocoa对象声明/实例化为存储的属性而不是局部变量?

[英]When should/must I declare/instantiate ReactiveCocoa objects as stored properties versus local variables?

(Applies to ReactiveCocoa 4 or maybe 3) (适用于ReactiveCocoa 4或3)

In most examples and cases I have seen, ReactiveCocoa objects like MutableProperty<TVal, TErr> or SignalProducer<TVal, TErr> that are involved in hooking up the user interface to data are at least instantiated in some setupBindings or similar method invoked in the constructor. 在我看到的大多数示例和案例中,将用户界面连接到数据所涉及的ReactiveCocoa对象(例如MutableProperty<TVal, TErr>SignalProducer<TVal, TErr>至少在某些setupBindings或构造函数中调用的类似方法中实例化。 。

I have experienced several cases in which I had non-working code that suddenly "just worked" when I moved the declaration of the object from the scope to a stored property or vice-versa. 我遇到过几种情况,当我将对象的声明从作用域移动到存储的属性时,我突然有了一些无法工作的代码,这些代码突然“起作用”,反之亦然。 For instance, in pseudo-code: 例如,用伪代码:

class Wtf {

    // doesn't work

    init() {
        let prop = MutableProperty<Dah, Dah>()...
        doSomethingWith(prop)
    }

    // also doesn't work

    private let prop: MutableProperty<Dah, Dah> = MutableProperty<Dah, Dah>(Dah())

    init() {
        doSomethingWith(prop)
    }    

    // works?

    private let prop: MutableProperty<Dah, Dah>

    init() {
        prop = MutableProperty<Dah, Dah>(Dah())
        doSomethingWith(prop)
    }
}

So it seems there are a few basic questions. 因此,似乎有一些基本问题。

Given some ReactiveCocoa object... 给定一些ReactiveCocoa对象...

  1. When should I declare it as a property ( let or var ) vs a local instance variable? 什么时候应该将其声明为属性( letvar )与局部实例变量?
  2. When should I instantiate it as a stored, computed, or other variant of property versus instance 我应何时将其实例化为属性与实例的存储,计算或其他变体
  3. When should it be a function return ? 什么时候应该return函数?

MutableProperty is a class . MutableProperty是一个class In other words: it has reference semantics. 换句话说:它具有参考语义。 Unlike Signal (whose lifetime depends on a termination event ), the lifetime of a property is defined by the owner. Signal (生命周期取决于终止事件 )不同, property的生命周期由所有者定义。 If no object is holding a reference to a property, it will be deallocated. 如果没有对象持有对属性的引用,则将其释放。

For that reason, the answer to your question would normally be to store it inside of another class. 因此,您问题的答案通常是将其存储在另一个类中。

A common thing to do is to keep the MutableProperty private , and only expose a readable one: 常见的做法是将MutableProperty private ,并且只公开可读的内容:

final class Owner {
    private let mutableProperty = MutableProperty<Type?>(nil)
    public var property: AnyProperty<Type?> {
        return AnyProperty(self.mutableProperty)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM