2012-06-24 169 views
0

好吧,我好像有一天進入學習目標c。我知道這是一個非常基本的問題,但它對我的學習會有很大的幫助。所以代碼只是一個基本的計數器,但我想添加一些東西,所以當計數器達到一定數量時,會出現不同的消息。我嘗試了許多不同的東西,但我失敗了。提前致謝。超級noob目標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]; { 

    } 


} 

回答

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 
} 

然後,您可以將您的其他方法更改爲類似的東西。

+0

實際上,在iOS上,您不需要IBAction方法的'sender'參數。有三種同樣有效的形式:沒有參數,1個參數('sender')或2個參數('(id)sender',(UIEvent *)event')。 –

+0

謝謝,我不太熟悉iOS上的Objective-C/Cocoa – TheAmateurProgrammer

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

    } 


}