Can/How Should I replace my KVO stuff with RC3?

Deadly 提交于 2019-12-12 07:35:54

问题


I'm trying to port an objc app which uses Facebook's KVOController, to Swift. I've been encouraged to look at RC3 as an alternate and more Swiftish approach. I've read some blogs and I'm encouraged to give this a try. But much of the docs and blogs seem to concentrate on sockets and timers as examples. So I have two simple questions right now:

1) Given an objc fragment like:

[self.KVOController observe: self.site keyPath: @"programs" options: NSKeyValueObservingOptionInitial block:^(id observer, id object, NSDictionary *change) {
    [self.tableView reloadData];
}];

What is the simple way to rewrite this with RC3 APIs? And what is the RC3 equivalent for self.KVOController unobserve: self.site that happens when that view unloads?

2) It's recommended that I use Carthage to grab the RC3 code. Can I intermix a Cartfile safely with a project that is using cocoa pods already for Alamofire and SwiftyJSON?


回答1:


Disclaimer :) I'm also new to the whole ReactiveCocoa concept and especially to RAC 3. I'm playing around with the new framework to learn, so my solution may not be the intended usage of the API. I'd be happy to receive feedback from others and learn the right way.

Here's what I could come up with for your first question: You can define the property you'd want to observe as a MutableProperty. Below is the most basic example with a String property. Assume you have a view model, it has a String property and you want to observe this in your view controller object.

ViewModel.swift

class ViewModel {
    var testProp = MutableProperty<String>("")
}

ViewController.swift

class ViewController: UIViewController {
    private let viewModel = ViewModel()

    override func viewDidLoad() {
        super.viewDidLoad()

        let testPropObserver = viewModel.testProp.producer
            testPropObserver.start(next: {value in
                println("new value \(value)")
            })

        viewModel.testProp.value = "you should see this in your log"
    }
}



回答2:


For the first question I can only guide you in the right direction. Take a look at the change log to 3.0 describing the shift away from RACObserve() to PropertyTypes. It's a little more explicit and it offers type safety. Here is the source, which I think is your best bet for figuring out how to implement it. You could also take a look at their test cases to see if they have built any tests for the PropertyType protocol and mimic how they've got it set up.

And yes, you'll have no trouble mixing Carthage and CocoaPods in one project, as Carthage is designed to be minimally intrusive. As long as you follow the instructions on their website you should be fine.



来源:https://stackoverflow.com/questions/29956622/can-how-should-i-replace-my-kvo-stuff-with-rc3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!