(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...
- When should I declare it as a property (
let
orvar
) vs a local instance variable? - When should I instantiate it as a stored, computed, or other variant of property versus instance
- When should it be a function
return
?
MutableProperty
is aclass
. In other words: it has reference semantics. UnlikeSignal
(whose lifetime depends on a termination event), the lifetime of aproperty
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: