如何在iOS中设置非零初始值?

时间:2012-09-28 02:00:20

标签: ios button synthesize

我的标题中提到了一个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语句。代码修复或指向在线文档中特定行的指针非常感谢。

1 个答案:

答案 0 :(得分:1)

每个对象都有一个在实例化时调用的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;
}