在我的应用程序中,我正在获取JSON数据。有时,应用程序将无法获取它,当我打印responseObject时,它返回()。我想制作一个if语句,以便在发生这种情况时,会显示UIAlertView。现在,我有一个if声明说如果self.jobs == nil,警报会出现,但是这不起作用。我真的很感激任何帮助!
- (void)viewDidLoad
{
[super viewDidLoad];
//Fetch JSON
NSString *urlAsString = [NSString stringWithFormat:@"https://jobs.github.com/positions.json?description=%@&location=%@", LANGUAGE, TOWN];
NSURL *url = [NSURL URLWithString:urlAsString];
NSURLRequest *request = [NSURLRequest requestWithURL: url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
//Parse JSON
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
self.jobs = (NSArray *)responseObject;
if(self.jobs != nil)
{
[self.tableView reloadData];
}
else
{
UIAlertView* alert_view = [[UIAlertView alloc]
initWithTitle: @"Failed to retrieve data" message: nil delegate: self
cancelButtonTitle: @"cancel" otherButtonTitles: @"Retry", nil];
[alert_view show];
}
}
//Upon failure
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
UIAlertView *aV = [[UIAlertView alloc]
initWithTitle:@"Error" message:[error localizedDescription] delegate: nil
cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[aV show];
}];
答案 0 :(得分:2)
听起来你回来了一个空响应,所以null check总是解析为true。尝试检查NSArray
的计数是否大于0而不是if(self.jobs != nil)
只需将if(self.jobs != nil)
更改为if([self.jobs count] > 0)
即可。
if([self.jobs count] > 0)
{
[self.tableView reloadData];
}
else
{
UIAlertView* alert_view = [[UIAlertView alloc]
initWithTitle: @"Failed to retrieve data" message: nil delegate: self
cancelButtonTitle: @"cancel" otherButtonTitles: @"Retry", nil];
[alert_view show];
}
在尝试执行计数以避免任何空引用异常之前,您可能还想进行空检查:
if(self.jobs != nil && [self.jobs count] > 0)