超级noob Objective C需要帮助

时间:2012-06-24 01:27:18

标签: objective-c

好的,所以我就像有一天学习目标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]; {

    }


}

2 个答案:

答案 0 :(得分: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
}

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

答案 1 :(得分: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]; {

    }


}