如果name是NSString,则_name和self.name有什么区别? [英] What is the difference between _name and self.name if name was a NSString
问题描述
如果我打电话
NSString *theNameToDisplay = _name;
或
NSString *theNameToDisplay = self.name;
我知道这可能是一个愚蠢的问题,但是我看到两个版本都使用了很多,并且在输出中没有发现差异吗?
I know it might be a silly question but I see both versions used a lot and I don't spot a difference in the output?
谢谢!
推荐答案
假定您在.m文件中具有这一行(并且没有任何替代方法可以直接访问_name)
Assume you have in your .m file this line (and don't have any overriden methods to direct access to _name)
@synthesize name = _name;
这意味着属性name
(self.name)在尝试访问它时将使用变量_name.在这种情况下,self.name
等于_name
It mean that property name
(self.name) will use variable _name when you try to access it. In this case self.name
is equal to _name
但是,如果您具有名称的动态属性,则如下所示:
But if you have dynamic property for name, something like this :
-(NSString)name{
return @"1234";
}
然后有一个区别. self.name
将始终返回1234,但_name不能等于此值.
then there is a difference. self.name
will always return 1234, but _name can be not equal to this value.
示例:
_name = @"555";
NSLog(_name);
NSLog(self.name);
结果:
2012-02-09 14:27:49.931 ExampleApp[803:207] 555
2012-02-09 14:27:49.933 ExampleApp[803:207] 1234
这篇关于如果name是NSString,则_name和self.name有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!