[英]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
对象...
let
or var
) vs a local instance variable? let
或var
)与局部实例变量? 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.