iOS First Application “self.userName = textField.text”. When to use self

南笙酒味 提交于 2019-12-03 22:28:38

Yes: textField.text is equivalent to self.textField.text in this case, because the synthesised getter simply returns the text field. Presumably Apple have gone for terseness because they want the code to be readable. I'd favour your approach though: with properties, it's a good habit to stick to the accessor methods, in case you ever want to customise them.

Note that the property is a separate entity from the internal variable. Apple's style is to give them both the same name, but some programmers like to separate the two concepts by giving internal variables underscore prefixes. In that case, _textField.text would give the same result here as self.textField.text. But only the second would be accessing your class's generated getter method for the text field - the first is exercising its right as a piece of class-internal code to access the internal variable directly.

No, they're not the same. In the code you provided, textField.text translates to [textField text], i.e. gets the text property of the object pointed to by the textField ivar. self.textField.text, on the other hand, translates to [[self textField] text], i.e. calls the current object's textField accessor, and calls the text accessor of the result.

The end result should usually be the same. It would be somewhat strange to have both an ivar and a property named textField and to have the property return something other than the ivar.

Are the two equivalent? Is the self unnecessary since the dot notation is there already which would already access the get methods?

As explained above, the results are similar, but the meaning is different. Using the accessor (i.e. self.textField.text) is the preferred style, but prefixing everything with self. can seem a little tedious too. One possible remedy if you're going to use a property repeatedly is to call the property accessor once and keep the result in a local variable.

Yes, Both are the same. You may use self.label.text or label.text (whichever) as both point to the same object.

You said it yourself, they are equivalent since self.label and label will point to the same object.

I would prefer to use the self.label version for more clarity but that's entirely a coding practice.

It's important to point out that there's a performance hit when your use the self.label since you're calling a method (which is not free). However, in most read-world cases, the performance hit is not noticeable (just good to know).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!