2010-01-05 73 views
0

我對Objective C比較新,需要一些數組幫助。從數組中檢索NSNumber

我有一個plist,它包含一個字典和一個NSNumber數組,後面增加更多數組到 。

NSMutableDictionary *mainArray = [[NSMutableDictionary alloc]initWithContentsOfFile:filePath]; 

NSArray *scoresArray = [mainArray objectForKey:@"scores"]; 

我需要從該數組檢索所有的值,並將其連接到哪個 我在界面生成器中設置了10個UILabels。我已經完成了以下操作來將NSNumber強制轉換爲字符串。

NSNumber *numberOne = [scoresArray objectAtIndex:0]; 
NSUInteger intOne = [numberOne intValue]; 
NSString *stringOne = [NSString stringWithFormat:@"%d",intOne]; 
scoreLabel1.text = stringOne; 

這似乎是一個非常漫長的方法,我不得不重複上述4行以上10次以檢索所有數組值。我可以使用for循環遍歷數組,並將所有值在輸出處轉換爲字符串?

任何信息將不勝感激。

使用stringValue的

回答

2
// create NSMutableArray* of score UILabel items, called "scoreLabels" 
NSMutableArray *scoreLabels = [NSMutableArray arrayWithCapacity:10]; 
[scoreLabels addObject:scoreLabel1]; 
[scoreLabels addObject:scoreLabel2]; 
// ... 

NSUInteger _index = 0; 
for (NSNumber *_number in scoresArray) { 
    UILabel *_label = [scoreLabels objectAtIndex:_index]; 
    _label.text = [NSString stringWithFormat:@"%d", [_number intValue]]; 
    _index++; 
} 

編輯

我不知道爲什麼你要註釋掉_index++。我沒有測試過這段代碼,所以也許我在某處丟失了某些東西。但我沒有看到_index++有什麼問題 - 這是增加計數器的非常標準的方法。

作爲替代創建scoreLabels陣列,可以確實檢索視圖控制器的子視圖(在這種情況下,您在界面生成器tag值添加到UILabel實例)的tag屬性。

假設tag值是可預測的 - 例如,每一UILabelscoreLabel1通過scoreLabel10標記有tag等於_index我們在for環路(0到9)使用的值 - 則可以引用UILabel直接:

// no need to create the NSMutableArray* scoreLabels here 
NSUInteger _index = 0; 
for (NSNumber *_number in scoresArray) { 
    UILabel *_label = (UILabel *)[self.view viewWithTag:_index]; 
    _label.text = [NSString stringWithFormat:@"%d", [_number intValue]]; 
    _index++; 
} 

使這一工作的關鍵是tag值必須爲UILabel唯一且必須的東西,你可以用-viewWithTag:參考。

上面的代碼非常簡單地假設tag的值與_index的值相同,但這不是必需的。 (它還假定UILabel實例是視圖控制器的view財產,子視圖,這將取決於你如何設置你的界面在界面生成器。)

有人寫加1000或一些其他的整數,可以讓你組的功能類型的子視圖在一起 - UILabel實例獲得1000,1001等等,而UIButton實例將獲得2000,2001等。

+1

如果將標籤添加到Interface Builder中的UILabel對象並使用viewWithTag:來檢索它們,您甚至可以擺脫scoreLabels數組。 – gerry3 2010-01-05 23:29:27

+0

謝謝亞歷克斯。只有在註釋掉_index ++時纔會生成。然後它返回在[scoreLabels addObject:scoreLabel1]中定義的標籤處數組中的最終Number; – user244295 2010-01-05 23:36:14

+0

使用-viewWithTag得到了這個工作,爲信息乾杯。 – user244295 2010-01-06 23:01:51

0

試...

scoreLabel1.text = [(NSNumber *)[scoresArray objectAtIndex:0] stringValue]; 
+0

感謝George。這工作正常。我想看看是否可以減少線路數量。使用上述內容仍然需要10行。 scoreLabel1。text = [(NSNumber *)[scoresArray objectAtIndex:0] stringValue]; scoreLabel2.text = [(NSNumber *)[scoresArray objectAtIndex:1] stringValue]; 等...... – user244295 2010-01-05 23:28:07

+0

請參閱下面的代碼片段。 – 2010-01-06 00:18:24

+0

哦,我看到了,沒有意識到問題是你需要重複數組中的項目數的代碼。只是覺得你需要一個班輪來設置數組值的UILabel文本。 Alex的解決方案很好。 – George 2010-01-06 15:07:24