Jose
Jose

Reputation: 93

How can I change a value of an NSObject at a keypath?

I have an NSObject with my profile information on it. An array with my favorite colours and favorite numbers, and a string with the name of my best friend.

{
favoriteColors =     (
    Green,
    Blue,
    Orange
);
favoriteNumbers =     (
    3,
    16,
    20
);
bestFriend = Josh;
}

Now, I want to update my profile information and replace my bestFriend to be "Alex".

I'm looking for a function that would do this:

[profileInformation replaceAtKeyPath:@"bestFriend" with: @"Alex"];

Many things I try give errors saying "Expression is not assignable", such as

[profileInformation valueForKeyPath:@"bestFriend"] = @"Alex";

Upvotes: 0

Views: 433

Answers (1)

A O
A O

Reputation: 5698

What you are looking for is called KVC (NSKeyValueCoding)

[profileInformation setValue:@"Alex" forKey:@"bestFriend"]

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSKeyValueCoding_Protocol/#//apple_ref/occ/instm/NSObject/setValue:forKeyPath:

Also note that NSKeyValueCoding is an informal protocol, which means that all NSObjects automatically conform to it. This is why Xcode autocomplete will allow you to call -setValue:forKey: on any Objective-C Foundation object

Upvotes: 2

Related Questions