Iphone 从数组中检索NSNumber

Iphone 从数组中检索NSNumber,iphone,c,arrays,nsnumber,Iphone,C,Arrays,Nsnumber,我对Objective C比较陌生,需要一些数组帮助 我有一个plist,它包含一个字典和一个NSNumber数组,还有更多的数组需要修改 稍后再添加 NSMutableDictionary *mainArray = [[NSMutableDictionary alloc]initWithContentsOfFile:filePath]; NSArray *scoresArray = [mainArray objectForKey:@"scores"]; 我需要从数组中检索所有的值,并将它们

我对Objective C比较陌生,需要一些数组帮助

我有一个plist,它包含一个字典和一个NSNumber数组,还有更多的数组需要修改 稍后再添加

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

NSArray *scoresArray = [mainArray objectForKey:@"scores"];
我需要从数组中检索所有的值,并将它们连接到10个UILabels 我已经在interface builder中进行了设置。为了将NSNumber转换为字符串,我执行了以下操作

NSNumber *numberOne = [scoresArray objectAtIndex:0];  
NSUInteger  intOne = [numberOne intValue];  
NSString *stringOne = [NSString stringWithFormat:@"%d",intOne];  
scoreLabel1.text = stringOne;
这似乎是一个非常冗长的方法,我必须重复上述4行10次才能检索所有数组值。我可以使用for循环在数组中迭代,并在输出中将所有值转换为字符串吗


任何信息都将不胜感激。

尝试使用stringValue

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

我不知道你为什么要注释掉
\u index++
。我还没有测试过这段代码,所以可能我遗漏了一些东西。但是我看不出
\u index++
有什么问题-这是一种非常标准的递增计数器的方法

作为创建
scoreLabels
数组的替代方法,您确实可以检索视图控制器子视图的
tag
属性(在本例中,是在Interface Builder中添加
tag
值的
UILabel
实例)

假设
标记
值是可预测的-例如,从
scoreLabel1
scoreLabel10
的每个
UILabel
都用一个
标记
值,该值等于我们在
for
循环(0到9)中使用的
\u索引
值-然后您可以直接引用
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++;
}
实现这一点的关键是
标记
值必须是
UILabel
的唯一值,并且必须是可以使用
-viewWithTag:
引用的值

上面的代码非常简单地假设
标记
值与
\u索引
值相同,但这不是必需的。(它还假定
UILabel
实例是视图控制器的
view
属性的子视图,这取决于您在interface Builder中设置界面的方式。)


有些人编写的函数可以添加1000或其他整数,允许您将子视图的类型分组在一起-
UILabel
instances得到1000、1001等等,而
UIButton
instances得到2000、2001等等。

谢谢。这个很好用。我想看看是否可以减少行数。使用上述命令仍然需要10行。scoreLabel1.text=[(NSNumber*)[scoresArray对象索引:0]stringValue];scoreLabel2.text=[(NSNumber*)[scoresArray对象索引:1]stringValue];ect…..哦,我明白了,我没有意识到问题是需要为数组中的项目数量重复代码。只是认为需要一行程序来设置数组值的UILabel文本。Alex的解决方案很好。如果将标记添加到Interface Builder中的UILabel对象,并使用viewWithTag:检索它们,您甚至可以摆脱scoreLabels数组。谢谢Alex。仅当我注释掉_index++时,才会生成此函数。然后返回数组中在[scoreLabels addObject:scoreLabel1]中定义的标签处的最终数字;
// 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++;
}