Question

I have an ivar which is mentioned in my header

@interface MyClass : UIView{
    int thistone;}
- (IBAction)toneButton:(UIButton *)sender;
@property int thistone;
@end

and I have synthesized it in the implementation:

@implementation MyClass
@synthesize thistone;
- (IBAction)toneButton:(UIButton *)sender {
if(thistone<4)
    {thistone=1000;}   // I hate this line.
    else{thistone=thistone+1; }  
}

I cannot find (or find in any manual) a way to set a nonzero initial value. I want it to start at 1000 and increase by 1 each time I press the button. The code does exactly what I intend, but I'm guessing there's a more proper way to do it that saves me the if/else statement above. Code fixes or pointers to specific lines in online documentation greatly appreciated.

Was it helpful?

Solution

Every object has a variant of the init method called at instantiation. Implement this method to do such setup. UIView in particular have initWithFrame: and initWithCoder. Best to override all and call a separate method to perform required setup.

For example:

- (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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top