简体   繁体   English

使用访问ivars。 符号

[英]Accessing ivars using the . notation

Assuming I have the following class. 假设我有以下课程。

@interface MyObj : NSObject{
   int age;   
}

-(void) setAge: (int) anAge;
-(int) returnAge;
@end

@implementation MyObj

-(void) setAge:(int) anAge{
  age = anAge;
}

-(int) returnAge{
  return age;
}

If I then want to assign a value to the age variable I could use the class method to do the following in main. 如果然后我想给age变量赋值,我可以使用class方法在main中执行以下操作。

MyObj *newObj = [MyObj new];
[newObj setAge:18];

However from messing around i've noticed that I seem to be able to directly access the ivar using the . 但是从乱七八糟的角度来看,我注意到我似乎能够使用来直接访问ivar。 notation. 符号。 I get no warning or error with this. 我对此没有任何警告或错误。

MyObj *newObj = [MyObj new];
newObj.age = 20;

The end result appears to be same for both but I feel like I shouldn't be using the . 两者的最终结果似乎相同,但我觉得我不应该使用。 notation to directly access ivars like this. 这样可以直接访问ivars的符号。

Should I be using getters and setters for all ivars or is directly accessing them like this ok? 我应该对所有ivars使用getter和setter还是像这样可以直接访问它们?

Thanks 谢谢

I personally avoid declaring instance variables and accessing them directly. 我个人避免声明实例变量并直接访问它们。 Instead I only declare properties using the @property statement. 相反,我仅使用@property语句声明属性。 Recent objective-c compilers than automatically introduce their belonging instance variables (auto synthesis). 最近的Objective-C编译器会自动引入其所属的实例变量(自动综合)。 Also getters and setters are then automatically added unless you declare such properties as read only or write only. 除非您将此类属性声明为只读或只写,否则还会自动添加getter和setter。

Using properties I never access the instance variables directly, except when implementing: 使用属性,我从不直接访问实例变量,除非在实现时:

  • init methods of their containing class 其包含类的init方法
  • when overwriting the getters/setters to retrieve/store the new value 覆盖获取器/设置器以检索/存储新值时
  • dealloc methods dealloc方法

In all other places I only refer to the property by using the self.propertyName notation. 在所有其他地方,我仅使用self.propertyName表示法引用该属性。 This implicitly will call the property's get and set method. 这将隐式调用属性的get和set方法。 This has the advantage that you can introduce get and set methods at a later moment without modifying your existing code. 这样做的好处是,您可以稍后引入get和set方法,而无需修改现有代码。

There are some good style guides that can tell you more about good objective-c code style such as: 有一些好的样式指南可以告诉您更多关于好的Objective-C代码样式的信息,例如:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM