Does not conform to protocol BindableObject - Xcode 11 Beta 4

前端 未结 3 1082
暗喜
暗喜 2021-02-07 03:43

Playing around with examples out there. Found a project that had a class that was a bindableobject and it didn\'t give any errors. Now that Xcode 11 beta 4 is out

3条回答
  •  -上瘾入骨i
    2021-02-07 03:52

    SwiftUI and Combine are two new frameworks that were announced at WWDC 2019. These two frameworks received a lot of attention at WWDC 2019, as evidenced by the number of sessions in which these technologies were featured.

    SwiftUI was introduced as

    a revolutionary, new way to build better apps, faster.

    Combine is described as

    a unified declarative framework for processing values over time

    Between the initial release and now (May, 2020, Swift 5.2), there have been some changes. Anyone new to SwiftUI and Combine, who may have watched the WWDC videos, may be left with a few questions as to how the two frameworks work together.

    Combine defines two interfaces: Publisher and Subscriber. A publisher sends events to subscribers. See sequence diagram below.

    If you start an application in SwiftUI, and then add combine, there will be no mention of a Publisher or a Subscriber, the two main players required to use Combine. Consider this very simple sample application below.

    import SwiftUI
    import Combine
    import SwiftUI
    
    final class ActorViewModel: ObservableObject {
        var name : String
        private var imageUrl : URL?
        //@Published
        private (set) var image : Image = Image(systemName: "photo") {
            willSet {
                DispatchQueue.main.async {
                    self.objectWillChange.send()
                }
            }
        }
    
        init(name: String, imageUrl: URL?) {
            self.name = name
            self.imageUrl = imageUrl
            self.fetchImage()
        }
    
        private func fetchImage() {
            guard nil != self.imageUrl,
                String() != self.imageUrl!.absoluteString else { return }
            let task = URLSession.shared.dataTask(with: self.imageUrl!) { (data, response, error) in
    
                guard nil == error , nil != response, nil != data,
                    let uiImage = UIImage(data: data!) else { return }
                    self.image = Image(uiImage: uiImage)
    
            }
            task.resume()
        }
    }
    
    struct ContentView: View {
        @ObservedObject var actor : ActorViewModel
    
        var body: some View {
            HStack {
                actor.image
                    .resizable()
                    .aspectRatio(contentMode: ContentMode.fit)
                    .frame(width: 60, height: 60)
                Text(actor.name)
            }
    
        }
    }
    
    struct ContentView_Previews: PreviewProvider {
        static var previews: some View {
            let actor = ActorViewModel(name: "Mark Hammill",
                                       imageUrl: URL(string: "https://m.media-amazon.com/images/M/MV5BOGY2MjI5MDQtOThmMC00ZGIwLWFmYjgtYWU4MzcxOGEwMGVkXkEyXkFqcGdeQXVyMzM4MjM0Nzg@._V1_.jpg"))
            return ContentView(actor: actor)
        }
    }
    

    The app preview via the canvas will look like this:

    The app uses a list view to display names and images of actors. There are just two classes to consider:

    1. ContentView -- the SwiftUI View subclass
    2. ActorViewModel -- the source of the data for the ContentView (called a ViewModel as it performs the role of VM in MVVM)

    The view has a reference to the actor object, as per the class diagram below.

    Although this example is using Combine, it is not immediately apparent. There is no mention of a Publisher or a Subscriber. What is going on?

    Answer: Looking at the class hierarchy fills in the missing gaps. The below class diagram explains the full picture (click on the image to see it in greater detail).

    Consulting Apple's documentation provides definitions for these types:

    • ObservedObject: A property wrapper type that subscribes to an observable object and invalidates a view whenever the observable object changes.
    • ObservableObject: A type of object with a publisher that emits before the object has changed. By default an ObservableObject synthesizes an objectWillChange publisher that emits the changed value before any of its @Published properties changes.
    • objectWillChange: A publisher that emits before the object has changed.
    • PassthroughSubject: A subject that broadcasts elements to downstream subscribers. As a concrete implementation of Subject, the PassthroughSubject provides a convenient way to adapt existing imperative code to the Combine model.

    First, consider what the @ObservedObject means. This is a property wrapper. A property wrapper reduces code duplication, and allows for a succinct syntax when declaring properties that hides how the property is stored and defined. In this case, the "Observed Object" is a property which observes another object.

    In other words, the property is a Subscriber (from the Combine Framework). The actor is (through the use of a property wrapper) is a Subscriber, which subscribes to a Publisher, but what is the Publisher in this scenario?

    The "Observable Object" is not itself the publisher, but rather has a publisher. The ActorViewModel conforms to the ObservableObject protocol. By doing so, it is provided with a publisher property called objectWillChange by an extension (which the framework provides on the ObservableObject protocol). This objectWillChange property is of type PassthroughSubject, which is a concrete type of the Publisher protocol. The passthrough subject has a property called send, which is a publisher method used to send data to any subscribers. So the property called "objectWillChange" is the Publisher.

    To recap, the Subscriber is the property called actor from the ContentView class, and the Publisher is the property objectWillChange from the ActorViewModel class. What about the need for the Subscriber to Subscribe to the Publisher? The "@ObservedObject" property wrapper is itself a Subscriber, so it must subscribe to the Publisher. But how does the View find out about changes sent to the Subscriber? That is handled by the SwiftUI framework, which we never see.

    Take-away: we don't need to worry about subscribing the view to the Publisher. On the other hand, we do need to worry about making sure the publisher tell the subscriber when something is about to change. When the image has been fetched from a remote server, and the data has been transformed into an image object, we call objectWillChange.send() to inform the View. Once the subscriber receives notification from the publisher that something is about to / has changed, it invalidates the view (which results in the view redrawing itself).

    Summary The way in which SwiftUI uses a ObservedObject PropertyWrapper does not on the surface give away the fact that Combine even exists in the equation. But by inspecting ObservedObject and ObservableObject, the underlying Combine framework is revealed, along with the design pattern:

    subscriber --> subscribing to a publisher --> which then publishes changes --> that are received by the subscriber

    References:

    • Blog Article
    • WWDC 2019 Session 204
    • WWDC 2019 Session 226

提交回复
热议问题