Re: Translating KVO-ed property to Swift
Re: Translating KVO-ed property to Swift
- Subject: Re: Translating KVO-ed property to Swift
- From: Charles Srstka <email@hidden>
- Date: Wed, 19 Apr 2017 12:56:55 -0500
> On Apr 17, 2017, at 7:40 AM, Jean-Daniel <email@hidden> wrote:
>
>> Le 17 avr. 2017 à 10:52, Quincey Morris <email@hidden <mailto:email@hidden>> a écrit :
>>
>> On Apr 17, 2017, at 01:43 , Jean-Daniel <email@hidden <mailto:email@hidden> <mailto:email@hidden <mailto:email@hidden>>> wrote:
>>>
>>> var version: String? {
>>
>> A slight correction: this declaration actually must be:
>>
>>> dynamic var version: String? {
>>
>>
>> otherwise KVO isn’t guaranteed to work in Swift.
>
> This is a good practice, but I don’t think this is required for computed property, especially if you take care of willChange/didChange manually, as the OP does.
Here’s the set of rules I recommend for writing KVO-compliant properties in Swift:
1. Always put @objc in front of every declaration involved, whether it’s the property itself or the static properties that are there to support it.
2. Stored properties need to call willChangeValue(forKey:) and didChangeValue(forKey:).
a. In most cases, just add “dynamic” to the property declaration, and Cocoa will automagically insert the needed calls.
b. If you call willChangeValue and didChangeValue manually, add the following static property, changing Foo to the property’s name. Since this is easy to misspell accidentally, it’s best to make an Xcode code snippet for it.
@objc private static let automaticallyNotifiesObserversOfFoo = false
3. Computed properties do not need to be dynamic, but should register their dependencies. The properties that form these dependencies also need to be KVO-compliant. To register dependencies, add the following static property. This is also helpful to set as an Xcode snippet to avoid typos.
@objc private static let keyPathsForValuesAffectingFoo: Set<String> = [#keyPath(bar)]
The snippet above tells Cocoa that the KVO-compliant property “foo” depends on the KVO-compliant property “bar”, meaning that if “bar” changes, “foo”’s observers will be notified as well.
Charles
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden