iOS将动态值添加到数组

时间:2015-04-17 03:02:08

标签: ios objective-c arrays ios7

我想在for循环中初始化的数组中添加UIImage的动态值,所以我创建了一个NSMutableArray来首先在for循环中设置对象,然后尝试从中检索值。 请您在添加动态值时查看我出错的地方以及应该最好的approch。

NSMutableDictionary * dic= [[NSMutableDictionary alloc]init];
NSMutableArray *cImages = [[NSMutableArray alloc]init];

for(int i=0; i<5; i++) {
    NSString * imageKey= [NSString stringWithFormat:@"image%i",i+1];              

    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString: [[results objectAtIndex:i]valueForKey:imageKey]]];
    UIImage *imageOne = [UIImage imageWithData:imageData];
    [dic setObject:imageOne forKey:imageKey];

}

for (NSString *key in dic) {
    NSString *sprite = [dic objectForKey:key];
    //adding below to the array
    [cImages addObject:sprite];             
}

1 个答案:

答案 0 :(得分:1)

将UIImage添加到可变数组有什么问题?

NSMutableArray *cImages = [[NSMutableArray alloc]init];

for(int i = 0; i < 5; i++)
{
    NSString *imageKey= [NSString stringWithFormat:@"image%i", i+1];
    UIImage *imageToAdd = [UIImage imageNamed:imageKey];
    [cImages addObject:imageToAdd];
}

// Using the images
for (UIImage *image in cImages)
{
    // Do whatever u want with each image.
}

如果你真的需要使用字典来访问名称为“image1,image2”等的UIImage,你可以这样做:

NSDictionary *dict = [[NSDictionary alloc] init];
for (int i = 0; i < 5; i++)
{
    NSString *imageKey = [NSString stringWithFormat:@"image%i", i+1];
    UIImage *image = [UIImage imageNamed:@"nameOfImageFile.png"];
    [dict setObject:image forKey:imageKey];
}

// Now you can access the UIImage values by their names (image1,image2,image3,image4,image5)
UIImage *imageToUse = [dict valueForKey:@"image1"];

(没有测试这些,但它是相当标准的。)