2014-09-30 87 views
0

我有一個名爲'_orderOfCardPlacement'的數組,在每次我的遊戲結束後都會將對象放入它中。這些對象是UIButton,它們有許多細節,比如setImage,setBounds,setCenter,對於這個問題setTag最重要。 setTag有兩種可能的結果,不管是'1'還是'2',它們最初都是用一個或另一個設置的,這可以通過另一種每輪調用的方法來改變。我需要做的是查看這個數組,看看有多少次'1'出現,並且出現了多少次'2',然後比較這個結果。所以如果'1'出現9次而'2'出現7次,那麼'1'在這種情況下獲勝。所以當我NSLog我的陣列(說一個回合後)我得到這個:比較一個數組中的兩個UIButton.tag元素objective-c

"<OBShapedButton: 0x7ff6f968e6a0; baseClass = UIButton; frame = (103 387.5; 150 135); opaque = NO; autoresize = RM+BM; userInteractionEnabled = NO; tag = 1; layer = <CALayer: 0x7ff6f968e8a0>>" 

和隨後的回合將添加更多的按鈕到陣列。但是我需要知道一旦這個數組已滿並且遊戲完成了如何訪問要比較的對象的'tag ='部分。感謝您的任何建議,如果有必要,請添加更多代碼!

下面是完整的解決方案,如果有更優雅的方式來做我在這裏做的事情,絕對有興趣知道!

//set the amount of cards each player has 
_howManyCardsForComputer = 0; 
_howManyCardsForPlayer = 0; 
for (int i = 0; i < _orderOfCardPlacement.count; i++) { 
    UIButton *auxButton = (UIButton *) [_orderOfCardPlacement objectAtIndex:i]; 
    NSInteger playerScore = auxButton.tag; 
    NSMutableArray *totalScoreArray = [[NSMutableArray alloc] init]; 
    [totalScoreArray addObject:[NSNumber numberWithInteger:playerScore]]; 
    for (int j = 0; j < totalScoreArray.count; j++) { 
     if ([[totalScoreArray objectAtIndex:j] isEqualToNumber:[NSNumber numberWithInteger:1]]) { 
      _howManyCardsForPlayer++; 
     } 
     if ([[totalScoreArray objectAtIndex:j] isEqualToNumber:[NSNumber numberWithInteger:2]]) { 
      _howManyCardsForComputer++; 
     } 
    } 
} 

_playerScore.text = [NSString stringWithFormat:@"Players cards %i", _howManyCardsForPlayer]; 
_playerScore.hidden = NO; 
_computerScore.text = [NSString stringWithFormat:@"Computers cards %i", _howManyCardsForComputer]; 
_computerScore.hidden = NO; 

回答

0

我不知道我是否清楚自己想要達到的目標。如果你的按鈕被存儲在一個NSMutableArray中,你可以通過創建第i個元素(在for循環中)來檢查它們的標籤並應用一個轉換。

NSMutableArray *arrayWithButtons = [[NSMutableArray alloc] init]; 
//... Fill the array 

//Check tags 
for(int i=0; i<numButtons; i++){ 
    UIButton *auxButton = (UIButton*) [arrayWithButton objectAtIndex:i]; 
    int auxTag = auxButton.tag; 
    //... perform the proper operations 
} 

我希望我理解得很好,這可以幫助你。

+0

謝謝!這很好,因爲它能夠通過nslog正確顯示標籤隨時間的變化,但是我需要加上所有'1'出現的次數和所有'2'出現次數。當我想出來時,我覺得自己會踢自己,但現在我被卡住了。 – JonHerbert 2014-09-30 20:29:42