gpt4 book ai didi

ios - UITableView 方法在 ViewDidLoad 之前调用

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:53:08 25 4
gpt4 key购买 nike

我正在尝试创建一个简单的天气应用程序,它使用 JSON 从 OpenweatherMap 获取数据并在 UITableView 中打印出来。但是,当我在下面执行此代码并在 numberOfRowsInSection 方法中设置断点时,它返回 0 行。在 numberOfRowsInSection 方法之后调用了 viewDidLoad 方法,这就是 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];
}

最佳答案

您可以在调用完成处理程序后重新加载数据,这将解决问题。

[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);
}];

关于ios - UITableView 方法在 ViewDidLoad 之前调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26156187/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com