我試圖創建一個簡單的天氣應用程序,它使用JSON從OpenweatherMap獲取數據並在UITableView中打印出來。但是,當我在下面執行此代碼並在numberOfRowsInSection
方法中設置斷點時,它將返回0行。不知怎的,viewDidLoad
方法在numberOfRowsInSection
方法之後被調用,這就是threeHoursForecast數組爲空的原因。任何人都可以幫助我嗎?UITableView方法被調用之前ViewDidLoad
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];
}
謝謝。它現在有效。我曾嘗試重新加載數據,但我把它放在請求的成功塊之外,所以它不起作用 – Harry 2014-10-02 16:10:10