iOS Object-Oriented Objective-C Diving Deeper - Classes, Properties and Methods Custom Classes Continued

Daniel Kokin
Daniel Kokin
1,496 Points

Setting and Getting question

I'm just now starting to understand the concept of setting and getting. However, I'm a bit confused about all the different ways. In the diner example there are few ways discussed:

//set values like this

 [table1 setSubtotal: 12.75];

 table1.subtotal = 12.75;

//get values like this

 float someValue = table1.subtotal;

However, I'm not sure how I would apply the following approach in a similar scenario. Is this just for elements with key value pairs? Can someone clear it up?

[grilledCheese setValue:<#(nullable id)#> forKey:<#(nonnull NSString *)#>]

1 Answer

Martin Wildfeuer
Martin Wildfeuer
Pro Student 11,071 Points

Let's assume grilled cheese is an instance of a class called Cheese. Cheese has a property of type string called country. This is what the setting this value would look like, just as in your example above. = "Switzerland";
[grilledCheese setCountry:"Switzerland"];
[grilledCheese setValue:"Switzerland" forKey:"country"];

Dot notation, that is, the first example, is the preferred way. This is explained in detail in the Apple Developer Docs: Key-Value Coding Fundamentals.

Hope that helps :)