user1477529
user1477529

Reputation: 1

Super noob Objective C help needed

Ok so I am like one day into learning objective c. I know this is a really basic question, but it will help me with my learning greatly. So the code is just a basic counter, but I want to add something to it so when the counter reaches a certain number, a different message appears. I have tried many different things but I failed. Thanks in advance.

#import "MainView.h"

@implementation MainView

int count = 0;

-(void)awakeFromNib {

    counter.text = @"count";

}

- (IBAction)addUnit {

    if(count >= 999) return;

    NSString *numValue = [[NSString alloc] initWithFormat:@"%d", count++];
    counter.text = numValue;
    [numValue release];
}

- (IBAction)subtractUnit {

    if(count <= -999) return;

    NSString *numValue = [[NSString alloc] initWithFormat:@"%d", count--];
    counter.text = numValue;
    [numValue release]; {

    }


}

Upvotes: 0

Views: 226

Answers (2)

TheAmateurProgrammer
TheAmateurProgrammer

Reputation: 9392

First of all, instead of putting the count as a global variable, it's more appropriate to put it in your interface instead. And regarding the question you have, your code should be changed to something like this.

- (IBAction)addUnit {

    //if(count >= 999) return;  Delete this line, there is absolutely no point for this line this line to exist. Basically, if the count value is above 999, it does nothing.

    NSString *numValue;
    if (count>=999)
    {
        //Your other string
    }
    else
    {
        numValue = [[NSString alloc] initWithFormat:@"%d", count++];   
    }
    counter.text = numValue;
    [numValue release];//Are you using Xcode 4.2 in ARC?  If you are you can delete this line
}

Then you can change your other method to something similar.

Upvotes: 1

Jamie
Jamie

Reputation: 6124

How about this?

#import "MainView.h"

@implementation MainView

int count = 0;
int CERTAIN_NUMBER = 99;


-(void)awakeFromNib {

    counter.text = @"count";

}

- (IBAction)addUnit {

    if(count >= 999) return;

    NSString *numValue = [[NSString alloc] initWithFormat:@"%d", count++];
    if(count == CERTAIN_NUMBER) {
        counter.text = numValue;
    }
    else {
        counter.text = @"A different message"
    }
    [numValue release];
}

- (IBAction)subtractUnit {

    if(count <= -999) return;

    NSString *numValue = [[NSString alloc] initWithFormat:@"%d", count--];
    if(count == CERTAIN_NUMBER) {
        counter.text = numValue;
    }
    else {
        counter.text = @"A different message"
    }
    [numValue release]; {

    }


}

Upvotes: 0

Related Questions