【发布时间】:2016-04-11 13:40:20
【问题描述】:
我正在使用 google places api 来搜索附近的餐馆。每个餐厅都显示在 UITableView 的一个单元格中。返回响应采用 JSON 格式。 JSON 包含的内容中有一个十进制数字,表示餐厅的评级。我想在单元格中显示评分。但是,有时餐厅没有评级,值为 (null)。所以我在 cellForRowAtIndexPath 方法中添加了一个检查,检查 rating 的值是否为 null。
if([dict valueForKey:kResponseRating] != [NSNull null])
{
NSNumber *rating = [dict valueForKey:kResponseRating];
[cell displayRating:rating];
}
else
{
NSLog(@"Value of rating is null");
}
当我运行应用程序时,tableView 仍然会在返回空值时立即崩溃,并且不会打印字符串“评级值为空”。因此,即使 json 中的值为 null,它也不会进入 else 语句。
好的,所以我检查了返回值是否为 NSString 类类型,而它不是。这是我用同样的方法做的:
if([[dict objectForKey:kResponseRating] isKindOfClass:[NSString class]])
{
NSLog(@"The return response is of type NSString");
}
而且它没有进入 if 语句。
这是计算评级并发布它的方法。该方法将评级四舍五入到最接近的 0.5,然后将其显示为 5 颗星。
-(void)displayRating:(NSNumber*)rating{
double rate = [rating doubleValue];
rate = round(rate * 2.0) / 2.0;
int counter = 0;
double compareVar = 1.0;
while(counter <= 4){
if(rate == 0.0)
{
imgRating[counter] = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"starempty.png"]];
[self.contentView addSubview:imgRating[counter]];
}
else
{
if(compareVar < rate)
{
imgRating[counter] = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"starfill.png"]];
[self.contentView addSubview:imgRating[counter]];
}
else if(compareVar == rate)
{
imgRating[counter] = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"starfill.png"]];
[self.contentView addSubview:imgRating[counter]];
}
else
{
if(compareVar - rate == 0.5)
{
imgRating[counter] = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"starhalffill.png"]];
[self.contentView addSubview:imgRating[counter]];
}
else
{
imgRating[counter] = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"starempty.png"]];
[self.contentView addSubview:imgRating[counter]];
}
}
counter++;
compareVar = compareVar + 1.0;
}
}
NSLog(@"This is rate: %f", rate);
}
此方法中的一行代码是否导致崩溃?
【问题讨论】:
-
如果其他条件有效?我的意思是检查 NSNull 是否有效?
-
我不这么认为。即使值为空,它也总是进入 if 语句。还有一件事,json 返回一个带有括号的空值,例如 (null)。
-
显示完整的崩溃日志并停止使用
valueForKey:。 -
使用objectForKey从字典中获取信息
-
你把这段代码放在哪里了?崩溃的原因是什么?
标签: ios objective-c json uitableview google-places-api