0

好的,所以我喜欢学习目标 c 的一天。我知道这是一个非常基本的问题,但它会极大地帮助我学习。所以代码只是一个基本的计数器,但我想添加一些东西,所以当计数器达到某个数字时,会出现不同的消息。我尝试了很多不同的事情,但我失败了。提前致谢。

#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]; {

    }


}
4

2 回答 2

1

首先,与其将计数作为全局变量,不如将其放在您的界面中更为合适。关于你的问题,你的代码应该改成这样。

- (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
}

然后,您可以将其他方法更改为类似的方法。

于 2012-06-24T01:50:56.183 回答
0

这个怎么样?

#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]; {

    }


}
于 2012-06-24T01:32:10.247 回答