gpt4 book ai didi

ios - 在 TableView 上通过NSURLSession读取数据

转载 作者:行者123 更新时间:2023-12-01 18:49:48 25 4
gpt4 key购买 nike

我尝试使用NSURLSession读取数据并返回tableview,但是即使我的代码也在viewArray中添加了数据

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [viewArray count];
}

返回0 !,这是我的代码:
- (void)viewDidLoad
{
[super viewDidLoad];
// Initialize table data
viewArray = [NSMutableArray arrayWithObjects: nil ];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:@"http://pizzy.sadrcom.com/foodCategories/pizzas/margarita"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"%@", json);
for (NSDictionary* groups in json ) {
GroupData *gInfo = [[GroupData alloc] init];
// Title
gInfo.title = [groups objectForKey:@"Title"];
// The Id
gInfo.theId = [groups objectForKey:@"Id"];

[viewArray addObject:gInfo];
}

}];
[dataTask resume];
}

最佳答案

在将对象添加到数组后,您没有调用[tableView reloadData];,并且随着数据异步的获取,那么第一次您的numberOfRowsInSection将在收到数据之前调用。
做这样的事情

- (void)viewDidLoad
{
[super viewDidLoad];
// Initialize table data
viewArray = [NSMutableArray arrayWithObjects: nil ];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:@"http://pizzy.sadrcom.com/foodCategories/pizzas/margarita"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"%@", json);
for (NSDictionary* groups in json ) {
GroupData *gInfo = [[GroupData alloc] init];
// Title
gInfo.title = [groups objectForKey:@"Title"];
// The Id
gInfo.theId = [groups objectForKey:@"Id"];
[viewArray addObject:gInfo];

}
dispatch_async(dispatch_get_main_queue(), ^{
[tableView reloadData];
});
}];
[dataTask resume];

}

关于ios - 在 TableView 上通过NSURLSession读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32113899/

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