What is the difference between _name and self.name if name was a NSString

前端 未结 6 1046
无人及你
无人及你 2020-12-22 13:26

What is the defference if I called

NSString *theNameToDisplay = _name;

or

NSString *theNameToDisplay = self.name;
<         


        
6条回答
  •  爱一瞬间的悲伤
    2020-12-22 13:48

    Assume you have in your .m file this line (and don't have any overriden methods to direct access to _name)

    @synthesize 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";
    }
    

    then there is a difference. self.name will always return 1234, but _name can be not equal to this value.

    Example:

    _name = @"555";
    NSLog(_name);
    NSLog(self.name);
    

    Result:

    2012-02-09 14:27:49.931 ExampleApp[803:207] 555
    2012-02-09 14:27:49.933 ExampleApp[803:207] 1234
    

提交回复
热议问题