salman siddiqui
salman siddiqui

Reputation: 902

Key Value Coding Use in Swift

I want to know the use of KVO in swift as I read in Apple Doc or any other online articles it states that it provides indirect access to properties and addressable via string. I have a set of doubts.

Upvotes: 1

Views: 651

Answers (1)

rob mayoff
rob mayoff

Reputation: 385610

If I can set the property directly via person.name = "John" they why to use a Set Value for key name = "John" indirectly

Please read “What is the point of key-value coding?”


Apple doc says key-value coding compliant can participate in a wide range of Cocoa technologies like Core Data. Why it's used and not in other frameworks

It's used where appropriate. It's used where it is helpful and the performance is acceptable. If it's not useful, or if its performance is too low, it's not used.


It is used during runtime or dynamic to set value. How it is?

Key-Value Coding uses the Objective-C runtime to look up getter and setter methods, and to find the types and locations of instance variables if the setters don't exist. See Friday Q&A 2013-02-08: Let's Build Key-Value Coding for a detailed analysis.

Apple documentation briefly describes the implementation of Key-Value Observing here. It's short enough to quote entirely:

Automatic key-value observing is implemented using a technique called isa-swizzling.

The isa pointer, as the name suggests, points to the object's class which maintains a dispatch table. This dispatch table essentially contains pointers to the methods the class implements, among other data.

When an observer is registered for an attribute of an object the isa pointer of the observed object is modified, pointing to an intermediate class rather than at the true class. As a result the value of the isa pointer does not necessarily reflect the actual class of the instance.

You should never rely on the isa pointer to determine class membership. Instead, you should use the class method to determine the class of an object instance.

Mike Ash gave a more detailed analysis in Friday Q&A 2009-01-23.


Is it TypeSafe and how?

It's not particularly type safe. For example, it doesn't stop you from storing a UIView in a property that's declared as NSString, or vice versa.

Its an Objective - C feature then why still used in Swift 4 with latest improvements with ./Type.property access and set

It's still used because most of Apple's SDK is still implemented in Objective-C, and because it lets you do things that you cannot do in Swift without much more “boilerplate” (manual, repetitive functions). The trade-off is that Objective-C is lower performance. In many, many cases, the lower performance of Objective-C (compared to Swift) is not a significant problem, and the increased dynamism is very helpful.

Upvotes: 2

Related Questions