【问题标题】:Retrieve NSNumber From Array从数组中检索 NSNumber
【发布时间】:2010-01-05 22:27:57
【问题描述】:

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

我有一个 plist,其中包含一个 Dictionary 和一个 NSNumber 数组,还有更多数组 稍后添加。

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

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

我需要从数组中检索所有值并将它们连接到 10 个 UILabel 我已经在界面生成器中进行了设置。我已完成以下操作将 NSNumber 转换为字符串。

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

这似乎是一个非常冗长的方法,我必须重复以上 4 行十次才能检索所有数组值。我可以使用 for 循环遍历数组,并将所有值在输出处转换为字符串吗?

任何信息将不胜感激。

【问题讨论】:

    标签: iphone c arrays nsnumber


    【解决方案1】:
    // 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 属性(在这种情况下,您在接口中添加tag 值的UILabel 实例建设者)。

    假设tag 的值是可预测的——例如,从scoreLabel1scoreLabel10 的每个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 属性的子视图,这取决于您在 Interface Builder 中设置界面的方式。)

    有些人编写的函数将 1000 或其他整数相加,允许您将子视图类型组合在一起 — UILabel 实例得到 1000、1001 等等,UIButton 实例得到 2000、2001 等等。

    【讨论】:

    • 如果在 Interface Builder 中将标签添加到 UILabel 对象并使用 viewWithTag: 检索它们,您甚至可以摆脱 scoreLabels 数组。
    • 谢谢亚历克斯。仅当我注释掉 _index++ 时才会构建。然后它返回数组中在 [scoreLabels addObject:scoreLabel1] 定义的标签处的最终数字;
    【解决方案2】:

    尝试使用 stringValue...

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

    【讨论】:

    • 谢谢乔治。这工作正常。我想看看是否可以减少行数。使用上述内容仍然需要 10 行。 scoreLabel1.text = [(NSNumber *)[scoresArray objectAtIndex:0] stringValue]; scoreLabel2.text = [(NSNumber *)[scoresArray objectAtIndex:1] stringValue];等等.....
    • 哦,我明白了,没有意识到问题是您需要为数组中的项目数量重复代码。只是认为您需要一个衬线来从数组值中设置 UILabel 文本。亚历克斯的解决方案很好。
    猜你喜欢
    • 1970-01-01
    • 2013-04-16
    • 1970-01-01
    • 1970-01-01
    • 2017-10-19
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多