Search code examples
xcodexcode4nsstringnsnumber

Displaying image specific to NSString value


I'm trying to post a specific image if a specific value is called, and it is my understanding this is not working because NSNumber is not properly being converted to an NSString, but I am unsure if this is the problem. Through the use of NSLog, I see that the data is passing through, such as a rating of 4.5, in which case I would like to show four and a half stars, but the image does not post. I verified already that the view is linked up and everything is connected, but no dice. Code below. Feedback greatly appreciated!

- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
    [self setString];

    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];
    NSString *string1 = [dic objectForKey:@"name"];
    NSString *string2 = [[dic objectForKey:@"rating"]stringValue];

    NSLog(@"RATE STRING ---> %@", string2);

    if (string2 == @"0")
    {
        UIImage *img = [UIImage imageNamed:@"zerorate.png"];
        [imageView2 setImage:img];
    }
    if (string2 == @"1")
    {
        UIImage *img = [UIImage imageNamed:@"onerate.png"];
        [imageView2 setImage:img];
    }
    if (string2 == @"1.5")
    {
        UIImage *img = [UIImage imageNamed:@"onehalfrate.png"];
        [imageView2 setImage:img];
    }
    if (string2 == @"2")
    {
        UIImage *img = [UIImage imageNamed:@"tworate.png"];
        [imageView2 setImage:img];
    }
    if (string2 == @"2.5")
    {
        UIImage *img = [UIImage imageNamed:@"twohalfrate.png"];
        [imageView2 setImage:img];
    }
    if (string2 == @"3")
    {
        UIImage *img = [UIImage imageNamed:@"threerate.png"];
        [imageView2 setImage:img];
    }
    if (string2 == @"3.5")
    {
        UIImage *img = [UIImage imageNamed:@"threehalfrate.png"];
        [imageView2 setImage:img];
    }
    if (string2 == @"4")
    {
        UIImage *img = [UIImage imageNamed:@"fourrate.png"];
        [imageView2 setImage:img];
    }
    if (string2 == @"4.5")
    {
        UIImage *img = [UIImage imageNamed:@"fourhalfrate.png"];
        [imageView2 setImage:img];
    }
    if (string2 == @"5")
    {
        UIImage *img = [UIImage imageNamed:@"fiverate.png"];
        [imageView2 setImage:img];
    }
        [[self myTableView] reloadData];
}

Solution

  • The value for string2 == @"0" is undefined. Try if ([string2 isEqualToString:@"0"]).

    Also, you might consider naming your png files after the value you're getting back. Then you could just do:

    UIImage *img = [UIImage imageNamed:string2];
    [imageView2 setImage:img];
    

    If this doesn't resolve the issue, what happens when you po string2 in the debugger? What happens when you po img after it's set, and what happens when you po imageView2?