iOS第一应用程序" self.userName = textField.text& quot.何时使用自我 [英] iOS First Application "self.userName = textField.text". When to use self

查看:69
本文介绍了iOS第一应用程序" self.userName = textField.text& quot.何时使用自我的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是Apple您的第一个iOS应用程序"文档中的代码段.

Here is a code snippet from Apple's "Your First iOS Application" document.

- (IBAction)changeGreeting:(id)sender {

self.userName = textField.text;

NSString *nameString = self.userName;
if ([nameString length] == 0) {
    nameString = @"World";
}
NSString *greeting = [[NSString alloc] initWithFormat:@"Hello, %@!", nameString];
label.text = greeting;
[greeting release];
}

我知道self.username会调用综合set方法(这很重要,因为它具有复制标志).

I understand that self.username calls the synthesized set method (important since it has a copy flag).

为什么textField.text和label.text不是self.textField.text和self.label.text.

Why is textField.text and label.text not self.textField.text and self.label.text.

两个相等吗?自已是否不必要,因为已经存在可以使用get方法的点符号了?

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

推荐答案

不,它们不一样.在您提供的代码中, textField.text 转换为 [textField text] ,即获取<指向的对象的 text 属性.code> textField ivar.另一方面, self.textField.text 会转换为 [[self textField] text] ,即调用当前对象的 textField 访问器,并调用结果的 text 访问器.

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.

最终结果通常应该是相同的.同时拥有一个ivar和一个名为 textField 的属性,并使该属性返回除ivar之外的其他内容,这有点奇怪.

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.

两个相等吗?是自我不需要,因为点符号是已经在那里访问get方法?

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

如上所述,结果相似,但含义不同.首选使用访问器(即 self.textField.text ),但为所有内容加上 self.似乎也有些乏味.如果要重复使用属性,一种可能的解决方法是调用属性访问器一次,并将结果保存在局部变量中.

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.

这篇关于iOS第一应用程序&quot; self.userName = textField.text&amp; quot.何时使用自我的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆