显示数组内容

时间:2012-02-06 18:09:41

标签: objective-c ios arrays text

我已经加载了一个数组:

currentBackground=4;
bgImages = [[NSArray alloc] initWithObjects:
            [UIImage imageNamed:@"mystery_01 320x460"],
            [UIImage imageNamed:@"mystery_02 320x460"],
            [UIImage imageNamed:@"mystery_03 320x460"],
            [UIImage imageNamed:@"mystery_04 320x460"],
            [UIImage imageNamed:@"mystery_05 320x460"],
            nil];

现在我想在标签中显示当前显示的图像的文件名。我想:

 mainLabel.text = [NSString stringWithFormat:@"bgImages= %@",[bgImages objectAtIndex:currentBackground]];

会工作,但我得到的只是十六进制代码。我有一个按钮可以很好地滚动图像。但是,当我尝试显示图像名称时,我得到的就是我认为的名称所在的地址。

思考。

1 个答案:

答案 0 :(得分:1)

执行此操作时,[bgImages objectAtIndex:currentBackground] - 您将获得UIImage的实例。当你执行stringWithFormat时,你是正确的,它正在打印图像的地址,仅此而已。

不幸的是,没有办法从UIImage实例中取出图像的“名称”,所以你可能不得不这样做:

currentBackground=4;
bgImages = [[NSArray alloc] initWithObjects:
            [UIImage imageNamed:@"mystery_01 320x460"],
            [UIImage imageNamed:@"mystery_02 320x460"],
            [UIImage imageNamed:@"mystery_03 320x460"],
            [UIImage imageNamed:@"mystery_04 320x460"],
            [UIImage imageNamed:@"mystery_05 320x460"],
            nil];
bgImageNames = [[NSArray alloc] initWithObjects:
                @"mystery_01 320x460",
                @"mystery_02 320x460",
                @"mystery_03 320x460",
                @"mystery_04 320x460",
                @"mystery_05 320x460",
                nil];

然后做:

mainLabel.text = [NSString stringWithFormat:@"bgImages= %@",[bgImageNames objectAtIndex:currentBackground]];

或者将bgImages数组的创建包起来,你甚至可以聪明地做到这一点:

currentBackground=4;
bgImageNames = [[NSArray alloc] initWithObjects:
                @"mystery_01 320x460",
                @"mystery_02 320x460",
                @"mystery_03 320x460",
                @"mystery_04 320x460",
                @"mystery_05 320x460",
                nil];
NSMutableArray *newBgImages = [NSMutableArray arrayWithCapacity:0];
for (NSString *image in bgImageNames) {
    [newBgImages addObject:[UIImage imageNamed:image]];
}
bgImages = [NSArray arrayWithArray:newBgImages];