Objective c 使用访问IVAR。符号
假设我有下面的课程Objective c 使用访问IVAR。符号,objective-c,ivars,Objective C,Ivars,假设我有下面的课程 @interface MyObj : NSObject{ int age; } -(void) setAge: (int) anAge; -(int) returnAge; @end @implementation MyObj -(void) setAge:(int) anAge{ age = anAge; } -(int) returnAge{ return age; } 如果我想给年龄变量赋值,我可以使用class方法在main中执行以下操作
@interface MyObj : NSObject{
int age;
}
-(void) setAge: (int) anAge;
-(int) returnAge;
@end
@implementation MyObj
-(void) setAge:(int) anAge{
age = anAge;
}
-(int) returnAge{
return age;
}
如果我想给年龄变量赋值,我可以使用class方法在main中执行以下操作
MyObj *newObj = [MyObj new];
[newObj setAge:18];
然而,从混乱中我注意到,我似乎能够直接访问ivar使用。符号我没有收到任何警告或错误
MyObj *newObj = [MyObj new];
newObj.age = 20;
最终的结果似乎是相同的,但我觉得我不应该使用。这样直接访问IVAR的符号
我应该对所有IVAR使用getter和setter还是像这样直接访问它们
谢谢我个人避免声明实例变量并直接访问它们。相反,我只使用
@property
语句声明属性。最近的objective-c编译器会自动引入它们所属的实例变量(自动合成)。此外,除非您将此类属性声明为只读或只写,否则会自动添加getter和setter
使用属性时,我从不直接访问实例变量,除非实现:
其包含类的方法init
- 覆盖getter/setter以检索/存储新值时
方法dealloc
self.propertyName
符号来引用属性。这将隐式调用属性的get和set方法。这样做的好处是,您可以在稍后引入get和set方法,而无需修改现有代码
有一些好的样式指南可以告诉您关于好的objective-c代码样式的更多信息,例如:
newObj->age
Dot syntax不直接访问实例变量。这只是编写访问器方法调用的另一种方法。为了证明这一点,请尝试使实例变量的名称与访问器方法名称中反映的属性名称不同。