如何将JSON追加到自定义类数组?循环外数组无法访问及TableView加载问题求助
问题分析与解决方案
这是典型的异步网络请求导致的时序问题,我来帮你拆解清楚:
问题根源
Alamofire的request方法是异步执行的——你调用getTheJasonData后,代码会立刻往下走,而闭包responseJSON里的逻辑要等网络请求完成(拿到服务器返回)才会执行。所以你在循环外访问channelArray或者尝试加载TableView时,请求还没结束,数组根本还没被填充数据,自然看不到内容。而循环内部能访问,是因为那段代码是在请求完成后才跑的,此时数组已经被追加元素了。
解决步骤
- 确保
channelArray是你的ViewController(或相关类)的成员变量(你代码里应该已经是了,但要确认它的作用域); - 在网络请求完成、数组填充完毕后,回到主线程刷新TableView(UI操作必须在主线程执行);
- 可选:处理请求失败的场景,给用户友好提示。
修改后的代码示例
// 先确保channelArray是类成员变量 var channelArray: [StaitonChannel] = [] func getTheJasonData(baseUrl: String) { Alamofire.request(baseUrl, method: .get).responseJSON { response in // 每次请求前清空旧数据,避免重复追加 self.channelArray.removeAll() if response.result.isSuccess { let json = JSON(response.result.value!) if let items = json.array { for item in items { let stationName = item["acf"]["station_name"].stringValue let stationDescription = item["acf"]["description"].stringValue let stationLogo = item["acf"]["logo"]["sizes"]["thumbnail"].stringValue let stationStreamUrl = item["acf"]["stream_url"].stringValue let newChannel = StaitonChannel(name: stationName, description: stationDescription, logo: stationLogo, streamUrl: stationStreamUrl) self.channelArray.append(newChannel) } // 请求成功且数组填充完成后,回到主线程刷新TableView DispatchQueue.main.async { self.tableView.reloadData() } } } else { print("Cannot get json data from the site") // 可选:请求失败时也回到主线程更新UI(比如显示错误提示或空状态) DispatchQueue.main.async { self.tableView.reloadData() } } } }
额外注意事项
- 记得在TableView的数据源方法(
numberOfRowsInSection、cellForRowAt)里正确使用channelArray的数据; - 每次请求前清空数组,避免多次请求导致数据重复堆积;
- 永远不要在子线程更新UI,所以必须用
DispatchQueue.main.async包裹所有UI操作。
内容的提问来源于stack exchange,提问作者Gayan Chanaka
相关产品推荐
相关产品推荐

