Search code examples
iosobjective-ciphonekvc

Using key-value coding (KVC) to obtain a UIImage but doesn't work when setting picture to it


My code:

for (int index = 1; index < [[firstPageJSONData objectForKey:@"pillars"] count] ; index++) {
        NSString *rotaryName = [NSString stringWithFormat:@"rotaryImage%d", index];
        UIImage *rotaryWheel = [self.wheelView valueForKey:rotaryName];
        NSString *urlStringImage2 = [[[firstPageJSONData objectForKey:@"pillars"] objectAtIndex:index] objectForKey:@"image_url"];
        NSData *imageData2 = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: urlStringImage]];
        rotaryWheel =  [UIImage imageWithData: imageData];
    }

However this code works, but it's way too lengthy and looks horrible.

        NSString *urlStringImage = [[[firstPageJSONData objectForKey:@"pillars"] objectAtIndex:0] objectForKey:@"image_url"];
        NSData *imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: urlStringImage]];
        self.wheelView.rotaryImage1 = [UIImage imageWithData:imageData];
        NSString *urlStringImage = [[[firstPageJSONData objectForKey:@"pillars"] objectAtIndex:1] objectForKey:@"image_url"];
        NSData *imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: urlStringImage]];
        self.wheelView.rotaryImage2 = [UIImage imageWithData:imageData];

Also I would need to do this 12 times!


Solution

  • change as below

    for (int index = 1; index < [[firstPageJSONData objectForKey:@"pillars"] count] ; index++) {
        NSString *rotaryName = [NSString stringWithFormat:@"rotaryImage%d", index];
        NSString *urlStringImage2 = [[[firstPageJSONData objectForKey:@"pillars"] objectAtIndex:index] objectForKey:@"image_url"];
        NSData *imageData2 = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: urlStringImage]];
        [self.wheelView setValue:[UIImage imageWithData: imageData] forKey:rotaryName];
    }