我有一个 ivar 在我的标题中提到
@interface MyClass : UIView{
int thistone;}
- (IBAction)toneButton:(UIButton *)sender;
@property int thistone;
@end
我已经在实现中合成了它:
@implementation MyClass
@synthesize thistone;
- (IBAction)toneButton:(UIButton *)sender {
if(thistone<4)
{thistone=1000;} // I hate this line.
else{thistone=thistone+1; }
}
我找不到(或任何手册中找到)设置非零初始值的方法。我希望它从 1000 开始,每次按下按钮时增加 1。 代码完全符合我的意图,但我猜有一种更合适的方法可以节省我上面的 if/else 语句。 非常感谢在线文档中的代码修复或指向特定行的指针。
每个对象都有一个在实例化时调用的 init
方法的变体。实现此方法以执行此类设置。特别是UIView有initWithFrame:
和initWithCoder
。最好覆盖所有并调用单独的方法来执行所需的设置。
例如:
- (void)commonSetup
{
thisTone = 1000;
}
- (id)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame])
{
[self commonSetup];
}
return self;
}
- (id)initWithCoder:(NSCoder *)coder
{
if (self = [super initWithCoder:coder])
{
[self commonSetup];
}
return self;
}