Dil*_*han 0 objective-c objective-c-runtime
我大部分时间都看过这段代码.这里定义了两个变量名,并且在实现中通过赋值进行合成.做这样的事情的目的是什么?喜欢保留2个单独的变量名称.这是一种惯例吗?
Test.h
@interface Test {
id<something> _variable1;
}
@property (nonatomic, retain) id<something> variable2;
Run Code Online (Sandbox Code Playgroud)
Test.m
@synthesize variable2 = _variable1
Run Code Online (Sandbox Code Playgroud)
只有一个变量.命名的东西variable2实际上是一个属性,它基本上是get/set方法对的语法快捷方式.定义属性时,可以显式写入get/set方法...
- (void)setVariable2:(id<something>)value {
if (_variable1 != value) {
[_variable1 release];
_variable1 = [value retain];
}
}
- (id<something>)variable2 {
return _variable1;
}
Run Code Online (Sandbox Code Playgroud)
...或者使用@synthesize构造自动生成上述方法,从而避免了大量的单调输入.(它还会释放代码以在销毁对象时释放_variable1,这里我没有包含它.)
但是,有时您可能希望以默认方式实现这些方法中的一个或另一个.在这种情况下,你会自己编写.您甚至可以混合使用@synthesize其中一种方法的自定义版本.