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

前端 未结 6 1027
无人及你
无人及你 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:58

    See the other answers about the setter part of properties, this is about getters:

    Normally, there is no difference in using the getter (self.name) or the ivar directly (_name, name, name_ depending on your taste).

    However, there might be cases where something (semi-)intelligent is happening under the hood, and the getter hides some magic. Imagine this custom getter:

    -(NSString*)name
    {
        if ( _name == nil ) return @"No name set";
        return _name;
    }
    

    Or imagine that you rework your class and the _name ivar gets dropped in favor of a person property encompassing more information, and you want your code to still work without much hassle:

    -(NSString*)name
    {
        return self.person.name;
    }
    

    People may or may not like such an approach, but that is outside the scope of this question. The point is, it may happen. So the better choice is to always use the getter.

提交回复
热议问题