我需要检查我的值是否包含“false”或字符串。
JSON:
{"success":true,"name":[{"image":false},{"image":"https:\/\/www.url.com\/image.png"}]}
我的代码:
NSData *contentData = [[NSData alloc] initWithContentsOfURL:url];
NSDictionary *content = [NSJSONSerialization JSONObjectWithData:contentData options:NSJSONReadingMutableContainers error:&error];
NSLog向我显示第一个图像值:
NSLog(@"%@", content);
image = 0;
我有一个UICollectionView,我想从URL设置图像。 如果值“image”为false,我想放置另一个图像,但我不知道如何检查它是否为假。
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
if ([[[content objectForKey:@"name"] objectAtIndex:indexPath.row] objectForKey:@"image"] == nil)
我也试过“== false”“== 0”,但没有任何效果。
有人有想法吗?
答案 0 :(得分:2)
拆分代码,使其更易于阅读和调试。似乎“图像”的价值要么是一个bool(作为NSNumber
),要么是一个url(作为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
}
答案 1 :(得分:0)
当false
加入JSON时,它会被反序列化为NSNumber
,其中包含布尔false
。您可以按如下方式进行比较:
// 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
}