美文网首页
self.variable 和 _variable 的区别

self.variable 和 _variable 的区别

作者: xkevin | 来源:发表于2016-07-14 16:42 被阅读35次
之前习惯于_variable这样访问变量,因为编写的代码量少~ 但实际上是有区别的
  1. self.variable 会调用getter或setter方法,
  2. 而_variable 是直接访问实例变量

[建议除过init方法,和自定义的set 方法内,都使用self访问,因为如果在getter 和setter 中做了额外的判断和处理,那直接访问就会跳过这部分]

具体来看代码:
在.h文件中声明一个属性

@property (nonatomic, strong) NSString *testStr;

在.m文件中重写了该testStr属性的setter方法

- (void)setTestStr:(NSString *)testStr {
_testStr = [NSString stringWithFormat:@"hello %@",testStr];
}

在方法体里用两种不同的方式去赋值

  //在method体内访问 testStr
  self.testStr = @"abc";
  NSLog(@"self.testStr:%@",self.testStr);// hello abc
  _testStr = @"abc";
  NSLog(@"_testStr:%@",_testStr);// abc

相关文章

网友评论

      本文标题:self.variable 和 _variable 的区别

      本文链接:https://www.haomeiwen.com/subject/bxpejttx.html