Ios 将UIApplicationLegate方法转换为RxSwift观测值
在RxSwift/RxCocoa中,您可以为委托创建反应式包装(例如,Ios 将UIApplicationLegate方法转换为RxSwift观测值,ios,swift,observable,uiapplicationdelegate,rx-swift,Ios,Swift,Observable,Uiapplicationdelegate,Rx Swift,在RxSwift/RxCocoa中,您可以为委托创建反应式包装(例如,UIScrollViewDelegate或CLLocationManagerDelegate),以便为某些委托方法启用Rx可观察序列 我正试图为uiapplicationelegate方法applicationdidebecomeactive: 到目前为止,我尝试的方法非常简单,与RxCocoa中包含的DelegateProxy子类类似 我创建了我的DelegateProxy子类: class RxUIApplicationD
UIScrollViewDelegate
或CLLocationManagerDelegate
),以便为某些委托方法启用Rx可观察序列
我正试图为uiapplicationelegate
方法applicationdidebecomeactive:
到目前为止,我尝试的方法非常简单,与RxCocoa中包含的DelegateProxy
子类类似
我创建了我的DelegateProxy
子类:
class RxUIApplicationDelegateProxy: DelegateProxy, UIApplicationDelegate, DelegateProxyType {
static func currentDelegateFor(object: AnyObject) -> AnyObject? {
let application: UIApplication = object as! UIApplication
return application.delegate
}
static func setCurrentDelegate(delegate: AnyObject?, toObject object: AnyObject) {
let application: UIApplication = object as! UIApplication
application.delegate = delegate as? UIApplicationDelegate
}
}
以及ui应用程序的接收扩展:
extension UIApplication {
public var rx_delegate: DelegateProxy {
return proxyForObject(RxUIApplicationDelegateProxy.self, self)
}
public var rx_applicationDidBecomeActive: Observable<Void> {
return rx_delegate.observe("applicationDidBecomeActive:")
.map { _ in
return
}
}
}
当我启动我的应用程序时,“Active!”被打印出来,然后我在RxCocoa的\u RXDelegateProxy\uxDelegateProxy
类中出现以下崩溃:
有人知道问题出在哪里吗?或者有人成功地实现了类似于
rx_applicationIDbecomeactive?这看起来是RxSwift和内存管理的一个非常棘手的问题
DelegateProxyType
的默认实现将委托代理的实例(在本例中为rxuiapplicationedegateproxy
)设置为UIApplication
的委托
它还将原始的AppDelegate
存储为名为forwardToDelegate
的属性,因此所有委托方法仍然可以传递给它
问题在于,当设置新的应用程序委托时:
application.delegate = delegate as? UIApplicationDelegate
原来的一个被取消分配了!您可以通过覆盖AppDelegate
中的deinit
进行检查。有关原因已在中解释。由于属性forwardToDelegate
的类型为assign
,当属性指向解除分配的对象时,应用程序崩溃
我已经找到了解决办法。我真的不确定这是否是一个推荐的方法,所以请注意。您可以从rxuiapplicationedegateproxy
中的DelegateProxyType
重写方法:
override func setForwardToDelegate(delegate: AnyObject?, retainDelegate: Bool) {
super.setForwardToDelegate(delegate, retainDelegate: true)
}
在正常情况下,您不希望保留代理,因为它会导致保留周期。但是在这种特殊情况下,这不是问题:您的UIApplication
对象将始终存在,而您的应用程序仍然处于活动状态。究竟什么是aSelector
?aSelector=(SEL)“window”
您建议的解决方案确实解决了问题。非常感谢您花时间查找并解释问题!
override func setForwardToDelegate(delegate: AnyObject?, retainDelegate: Bool) {
super.setForwardToDelegate(delegate, retainDelegate: true)
}