我正在尝试创建一个简单的天气应用程序,它使用JSON从OpenweatherMap获取数据并在UITableView中打印出来。但是,当我执行下面的代码并在numberOfRowsInSection
方法设置断点时,它返回0行。不知怎的,在viewDidLoad
方法之后调用numberOfRowsInSection
方法,这就是为什么threeHoursForecast数组为空。有人可以帮我吗?
static NSString * const BaseURLString = @"http://api.openweathermap.org/data/2.5/forecast?q=Houston";
@interface HPViewController ()
@end
@implementation HPViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.threeHoursForecast = [[NSMutableArray alloc] init];
self.tableView.dataSource = self;
self.tableView.delegate = self;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:BaseURLString parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSArray *data = [responseObject objectForKey:@"list"];
for (NSDictionary *forecastPerThreeHours in data)
[self.threeHoursForecast addObject:[[forecastPerThreeHours valueForKey:@"main"] valueForKey:@"temp"]];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [self.threeHoursForecast count];
}
答案 0 :(得分:8)
您可以在调用完成处理程序后重新加载数据,这将解决问题。
[manager POST:BaseURLString parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSArray *data = [responseObject objectForKey:@"list"];
for (NSDictionary *forecastPerThreeHours in data)
[self.threeHoursForecast addObject:[[forecastPerThreeHours valueForKey:@"main"] valueForKey:@"temp"]];
//Add this line
[self.TableView reloadData];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
答案 1 :(得分:3)
post方法是异步的。您需要在成功的请求块中添加[self.tableView reloadData];
。
答案 2 :(得分:1)
manager POST:
是异步调用,因此您需要在获取JSON后重新加载数据。
[manager POST:BaseURLString parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSArray *data = [responseObject objectForKey:@"list"];
for (NSDictionary *forecastPerThreeHours in data)
[self.threeHoursForecast addObject:[[forecastPerThreeHours valueForKey:@"main"] valueForKey:@"temp"]];
// [NOTE]
[self.tableView reloadData];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];