Reputation: 948
The CKRecord
class specification in Swift says to use setObject:forKey:
to set the value of a CKRecord
. But I am seeing a lot of code examples with setValue:forKey:
which is part of NSValueCoding
protocol. So can someone explain what is the advantage of one over the other?
Upvotes: 1
Views: 544
Reputation: 285072
Unfortunately setValue:
is very often misused.
Easy Rule:
The designated method to set an object for a key in a key/value collection type is setObject:
or key subscription.
setValue:
is a key-value-coding method with a special meaning. For example you can set the same property of all dictionaries (or custom objects) in an array simultaneously with a single line. setValue:
can also be used to set a property in a custom class by literal key rather than using the appropriate setter.
For example the syntax
object.name = "foo"
and
object.setValue("foo", forKey:"name")
does basically the same.
One of the exceptions to use setValue:
is NSManagedObject
because this class relies heavily on key-value-coding.
Edit:
Summary (literal quotation of rmaddy's excellent comment, thanks):
Only use setValue:forKey:
when you have a clear, specific need to use key-value coding.
Upvotes: 3