2

I need to check if my value contains "false" or a string.

JSON:

{"success":true,"name":[{"image":false},{"image":"https:\/\/www.url.com\/image.png"}]}

My Code:

NSData *contentData = [[NSData alloc] initWithContentsOfURL:url];
NSDictionary *content = [NSJSONSerialization JSONObjectWithData:contentData options:NSJSONReadingMutableContainers error:&error];

NSLog shows me for the first image value:

 NSLog(@"%@", content);

image = 0;

I have a UICollectionView where I want to set an image from the URL. If the value "image" is false, i want to put an other image, but i dont know how to check if it is false.

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([[[content objectForKey:@"name"] objectAtIndex:indexPath.row] objectForKey:@"image"] == nil)

I also tried "== false" "== 0" but nothing worked.

Anyone has an idea?

1
  • 1
    "false" (when not enclosed in quotes) comes through as an NSNumber encoding a zero value. Commented Dec 22, 2014 at 17:26

2 Answers 2

2

Split your code up to make it easier to read and debug. And it seems the value of "image" will either be a bool (as an NSNumber) or a url (as an NSString).

NSArray *nameData = content[@"name"];
NSDictionary *imageData = nameData[indexPath.row];
id imageVal = imageData[@"image"];
if ([imageVal isKindOfClass:[NSString class]]) {
    NSString *urlString = imageVal;
    // process URL
else if ([imageVal isKindOfClass:[NSNumber class]) {
    NSNumber *boolNum = imageVal;
    BOOL boolVal = [boolNum boolValue];
    // act on YES/NO value as needed
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this works also like the code from dasblinkenlight but i can only accept one answer.
0

When false comes in JSON, it gets deserialized as NSNumber with Boolean false inside it. You can do your comparison as follows:

// This is actually a constant. You can prepare it once in the static context,
// and use everywhere else after that:
NSNumber *booleanFalse = [NSNumber numberWithBool:NO];
// This is the value of the "image" key from your JSON data
id imageObj = [[[content objectForKey:@"name"] objectAtIndex:indexPath.row] objectForKey:@"image"];
// Use isEqual: method for comparison, instead of the equality check operator ==
if ([booleanFalse isEqual:imageObj]) {
    ... // Do the replacement
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.