Heisenberg
Heisenberg

Reputation: 367

Changing UILabel's text

I'm currently following CS 193P, and I'm on lecture 2. If you've followed this class before, I'm where we just added a label to output the number of flips.

Here's the screenshot of the view and controller (original code from the lecture): original code

I notice the instructor is changing the flipsLabel's text from inside the setter for flipCount. But, I think it's easier/ more intuitive to just send a message to the flipsLabel object whenever touchCardButton method is being called. Here's the screenshot after modification: after modification

Can somebody explain the reason why the instructor wrote it that way? He said "And here's another great use of getters and setters, which is to keep UI in sync with a property"

Upvotes: 3

Views: 144

Answers (3)

Quang Hà
Quang Hà

Reputation: 4746

The purpose of his code is: Everytime you set a new value for flipCount property, the text of label also changed. You don't need to set label text again. Your code will be clear, and easy to modify after.

Upvotes: 2

Ricky
Ricky

Reputation: 10505

I started my iOS developer career from CS193P as well about 2+ years ago.

Just like KudoCC said above, if you use your method to set flipCount in 10 different places, then you will have to set self.flipsLabel in 10 different places as well. So, your method will have more lines of code while the professor's way is using less lines of code.

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

Upvotes: 3

KudoCC
KudoCC

Reputation: 6952

The content of self.flipsLabel only depends on flipCount property.

You may change the value of flipCount at more than one place afterwards, and if you work as the instructor said, you needn't update the content of 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 may change the value of flipCount at 100 places, in you intuitive way, you must add 100 times [self.flipsLabel setText:[....]], if you forget to add in one place, a bug is born.

Upvotes: 3

Related Questions