Search code examples
iosobjective-carraysios7

iOS Adding Dynamic Values to Array


I want to add dynamic values of UIImage in array which initialised in the for loop, So I created a NSMutableArray to set object first in for loop and later tried to retrieve values from that. Please can you look where I am going wrong and what should be best approch while adding the dynamic values.

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];             
}

Solution

  • What's wrong with just adding UIImage's to the mutable array?

    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.
    }
    

    If you really need to use a dictionary to access the UIImage's by the names "image1, image2" etc you can do this:

    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"];
    

    (haven't test these, but it's fairly standard).