Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"

like image 993
Heisenberg Avatar asked May 15 '26 03:05

Heisenberg


2 Answers

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.

like image 54
Ricky Avatar answered May 17 '26 18:05

Ricky


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.

like image 44
KudoCC Avatar answered May 17 '26 18:05

KudoCC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!