我对 Objective C 比较陌生,需要一些数组帮助。
我有一个 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 行十次才能检索所有数组值。我可以使用 for 循环来迭代数组,并将所有值在输出处转换为字符串吗?
任何信息将不胜感激。
最佳答案
// 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
数组的替代方法,您确实可以检索 View Controller subview 的 tag
属性(在本例中为 UILabel
实例(您在 Interface Builder 中添加标签
值)。
假设 tag
值是可预测的 - 例如,从 scoreLabel1
到 scoreLabel10
的每个 UILabel
都标记为一个 tag
等于我们在 for
循环中使用的 _index
值(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 Controller 的 view
属性的 subview ,这取决于您在 Interface Builder 中设置界面的方式。)
有些人编写了将 1000 或其他整数相加的函数,以便将 subview 的类型分组在一起 - UILabel
实例获得 1000、1001 等,UIButton
实例将得到 2000、2001 等。
关于iphone - 从数组中检索 NSNumber,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2009597/