0

I am getting some JSON data from a service, one property is a string to represent an image url, it seems what is returned is NULL, I do the check but XCode breaks before my if statement and generate an exception. this is my code below:

- (void)configureCellForAlbum:(Album *)album {

    self.albumTitle.text = album.albumTitle;
    self.artisteName.text = album.artisteName;
    NSURL *imageUrl = [NSURL URLWithString:album.thumbnail];
    if (imageUrl == nil) {
        self.albumThumbnail.image = [UIImage imageNamed:@"music_record"];
    }
    else {
        self.albumThumbnail.imageURL = imageUrl;
    }
}

the exception is

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSNull length]: unrecognized selector sent to instance.

How do I do the check so that if the value retured is null, it uses a local image but if not null to use the image string url that is returned?

nhgrif
  • 61,578
  • 25
  • 134
  • 173
T. Israel
  • 229
  • 2
  • 6
  • 16

2 Answers2

9

nil is returned by the dictionary if no object with that key was found.

An instance of NSNull is inserted by the JSON parser to indicate that a null-valued key was present.

You need to check whether the object you got back was really a string. You are failing to catch the case where there is an object but it is not a string.

E.g.

if ([albm.thumbnail isKindOfClass:[NSString class]])
    ... a string-form URL is present ...
else
    .... something else, or nothing, was found; use a fallback ...
Tommy
  • 99,986
  • 12
  • 185
  • 204
  • It seemed pretty clear to me that the asker understood approximately this much already. As for the final stretch, the question is a duplicate and should be marked as such rather than answered. – nhgrif Feb 25 '16 at 13:39
  • It doesn't seem clear to me. He seems to indicate that he expects a JSON null to turn into a nil. – Tommy Feb 25 '16 at 13:42
  • Took me all day to notice the difference. There are two signatures some of the NSFileManager offer. The one that takes URL and Path. My error was plugging in the NSURL into where it was asking for Path. – Manabu Tokunaga May 11 '18 at 22:29
0

I tried from other question which asked same that what you ask here.But you need to customize the code like above Tommy's code.

NSDictionary *dict = [[NSDictionary alloc]initWithObjectsAndKeys:@"iOS",@"language",nil];
id Value = [dict objectForKey:@"language"];
NSString *strLanguage = @"";
if (Value != [NSNull null]) {
  strLanguage = (NSString *)Value;
  NSLog(@"The strLanguage is - %@", strLanguage);
}

Output

The strLanguage is - iOS

Thank You nhgrif:-)

user3182143
  • 9,459
  • 3
  • 32
  • 39