简体   繁体   中英

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

(Applies to ReactiveCocoa 4 or maybe 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.

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

  1. When should I declare it as a property ( let or var ) vs a local instance variable?
  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 ?

MutableProperty is a 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. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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