简体   繁体   中英

Can ReactiveCocoa be used with pure c++ ViewModels?

The motivation is the sharing of view models across platforms (Android, Windows Phone).

For example, consider:

RAC(self.nameField,text) = RACObserve(self.viewModel, playerName);

What if self.viewModel is pure C++(11)?

Obviously C++ doesn't have properties, but perhaps it can be made to work somehow? Or is ReactiveCocoa coupled to Objective-C on both sides (naturally being coupled on the UI side is no big deal, as some other binding mechanism would have to be used for the relevant environment regardless).

Obviously C++ doesn't have properties, but perhaps it can be made to work somehow?

Wrap your C++ objects in Objective-C wrappers.

Or is ReactiveCocoa coupled to Objective-C on both sides (naturally being coupled on the UI side is no big deal, as some other binding mechanism would have to be used for the relevant environment regardless).

There are some UI-specific extensions to UIKit and AppKit in ReactiveCocoa, but the core of the library has no dependency on or knowledge of "the UI side" at all, but most of the functionality in ReactiveCocoa 2.x relies on runtime features in Objective-C objects.

RACObserve() is just a macro for a method that ultimately ends up calling -[NSObject rac_observeKeyPath:options:observer:block:] , which itself uses an Objective-C-specific technology called Key Value Observing . C++ objects don't support KVO out of the box, so they don't work out of the box with RACObserve() .

ReactiveCocoa relies on a Cocoa style implementation of the observer pattern, which in turn relies on the dynamic-dispatch nature of Objective-C.

In Cocoa observers work by performing isa-swizzling of a class (reassigning the class pointer to a runtime generated subclass. The sub-class overrides the setter method to notify an associated reference of observers when a property changes.

As C++ uses static/vtable style of dispatch, this style of method interception isn't supported. Therefore ReactiveCocoa observers won't work. So the answer is essentially no, ReactiveCocoa won't work for pure C++ classes, although the underlying principles could be applied, or you might look for an Rx library for C++.

Interestingly, Swift defaults also to static/vtable dispatch (though supports dynamic dispatch if you extend NSObject or use the @objc decoration). Here's a n article describing another style of observer for Swift .

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