Changing the text of the UILabel

I am currently following CS 193P and I am in lecture 2. If you have already followed this class, I just added a shortcut to output the number of flips.

Here is a screenshot of the view and controller (source code from the lecture): original code

I notice that the instructor is changing the flipsLabel text inside the setter for flipCount. But I find it easier or more intuitive to just send a message to the flipsLabel object whenever the touchCardButton method is called. Here is a screenshot after modification: after modification

Can someone explain the reason the instructor wrote it this way? He said, "And here's another big use of getters and setters that is to keep the UI in sync with the property."

+3


source to share


3 answers


I started my iOS developer career from CS193P and also about 2+ years ago.

Like KudoCC mentioned above, if you use your method to install flipCount

in 10 different locations, you will need to install self.flipsLabel

in 10 different locations. This way, your method will have more lines of code, while the professor's path uses fewer lines of code.



I personally think this is the art of programming. We have different ways to achieve the same in programming. But the less code you use in programming, the better.

+3


source


The content self.flipsLabel

only depends on the property flipCount

.

You can change the value flipCount

in more than one place after that, and if you are an instructor, you do not need to update the content self.flipsLabel

every time you change flipCount

.



You are in a simple user case, which may not matter how to implement it, but if you are in a complex user case, you can change the value flipCount

to 100 places, in an intuitive way, you have to add 100 times [self.flipsLabel setText:[....]]

, if you forgot to add in one location, an error will appear.

+3


source


The purpose of his code is that every time you set a new value for the flipCount property, the text of the label changes as well. You don't need to set the label text again. Your code will be clear and easy to change after.

+2


source







All Articles