Add a property observer on an existing property in an iOS library class

社会主义新天地 提交于 2019-12-23 02:08:15

问题


In my SpriteKit game, I want to add a property observer on the fieldBitMask property for the SKPhysicsBody of my sprites. I want to be informed when the fieldBitMask property changes so that I can take some action.

I overrode SKPhysicsBody but when I tried assigning the overridden class to a sprite node like a normal SKPhysicsBody object I got a bunch of errors. I also thought about making an extension for SKPhysicsBody, but Apple documentation says, “Extensions can add new functionality to a type, but they cannot override existing functionality.” So it would seem that I can't override the fieldBitMask property this way to make it a property observer.

I know how to create a property observer in a new custom class which I create. But what is the best way to add a property observer to an existing property in a class that is part of the Apple library?


回答1:


I think you can use the Key Value Observing. You can add observer to a property changing.
You should implement observeValue(forKeyPath:of:change:context:) method in your observer class.

Here you can find Swift example ("Key-Value Observing" part).




回答2:


You can subclass SKPhysicsBody like that:

class Subclass: SKPhysicsBody {
    override var fieldBitMask: UInt32 {
        didSet {
            print(fieldBitMask)
        }
    }
}


来源:https://stackoverflow.com/questions/46484188/add-a-property-observer-on-an-existing-property-in-an-ios-library-class

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