【问题标题】:Pull-to-refresh modifies array value?拉动刷新修改数组值?
【发布时间】:2026-02-06 19:40:01
【问题描述】:

我正在使用 Swift 在 iOS 上进行下拉刷新。
我有一个包含城市名称的数组,cityNames = ["Chicago", "New York City"]
我实现了一个下拉刷新来从互联网上获取温度数据。所以每次我触发下拉刷新时,它都会上网并获取cityNames数组中每个城市的温度。
这是拉动刷新的代码

var weatherDetail = [Weather]()
// Pull to refresh
func refreshData() {
    var cityNames = [String]()
    for (index, _) in weatherDetail.enumerate() {
        let info = weatherDetail[index]
        cityNames.append(info.cityName)
    }
    print(cityNames)
    weatherDetail.removeAll()
    for city in cityNames {
        self.forwardGeocoding(city)
    }
    weatherCityTable.reloadData()
    refreshControl.endRefreshing()
}

在上面的代码中,weatherDetail 是一个模型数组(我不知道如何表达这个,但Weather 是一个模型,其中包含城市名称、温度、日出时间、高/低温.
forwardGeocoding 是一个获取城市地理坐标的函数,然后发送请求以获取该城市的天气数据。
拉动刷新工作,我遇到的问题是,在我拉动的前 2,3 次,它没有问题。但是当我拉更多次时,数组会突然变为cityNames = ["Chicago", "Chicago"]
感谢您的帮助,如果您需要更多信息,请告诉我。
更新:
我删除了weatherDetail.removeAll(),尝试将相同的数据附加到数组中。刷新后,打印出"Chicago", "New York City", "Chicago", "Chicago"。如果我刷新它更多次,它会打印出类似"Chicago", "New York City", "Chicago", "Chicago", "Chicago", "Chicago"

【问题讨论】:

  • cityNames 数组不在您的代码中。怎么填的?
  • @Darko 谢谢指出,刚刚修改了代码。
  • 从给定的代码中可以看到一个问题:您只是附加到 cityNames 但永远不会删除它。
  • 也许您在刷新时尝试刷新?所以,也许添加一个 var isRefreshing 并且如果它没有更新就更新。
  • weatherDetail 数组中填充了什么?

标签: ios arrays swift uitableview pull-to-refresh


【解决方案1】:

forwardGeocoding 是同步的吗? weatherDetail 何时设置/更新?

在我看来,您在这里遇到了某种同步问题,可能会因延迟而加剧。

【讨论】:

    【解决方案2】:

    使用enumerate()append() 来做到这一点不是一个好方法,有一个更优雅和防错的方法来实现这一点:

    let cityNames:[String] = weatherDetail.map { weather -> String in
         weather.cityName
    }
    

    或者直接写:

    let cityNames:[String] = weatherDetail.map { $0.cityName }
    

    【讨论】:

      【解决方案3】:

      如果城市名称重复两次,则意味着weatherDetail 数组中的信息也重复了两次。在打印cityNames 之前尝试打印weatherDetail。如果weatherDetail 重复了两次,那么您应该找到将相同的Weather 对象添加两次的代码并消除它。

      出于测试目的,找到修改weatherDetail 的每个位置,并在这些语句之前放置weatherDetail.removeAll()。如果这样可以解决您的问题,请搜索将冗余信息添加到 weatherDetail 的代码。

      【讨论】:

      • 问题不是城市名称重复两次,而是被替换为相同的值。
      • 您是否尝试在cityNames 之前打印weatherDetail?它是否在所有元素中都包含相同的Weather 信息?您是否在包含 5-10 个对象的数组上测试了您的错误? cityNames 只是映射weatherDetail 的结果,所以我很确定你的weatherDetail 中有重复值,这是万恶之源。
      • 由于weatherDetail是用模型制作的,所以当我打印出来时,我得到的只是[<JWeather.Weather: 0x7fc3b346b540>, <JWeather.Weather: 0x7fc3b346ae00>]。当我用 5-10 个对象测试它时,数组将变为 ["Chicago", "Chicago", "Chicago", "New York", "New York", "Washington", "Washington", "Washington", "Beijing"] 而我最初放在 9 个不同的城市。
      • 循环打印weather.cityName,类似于:for weatherInfo in weatherDetail { print(weatherInfo.cityName) }。如果你看到重复值,那么问题出在你的 weatherDetail 数组中,你应该尝试一次又一次地找到放置相同值的位置。
      • 当我打印出来时,我得到了不同的城市名称,没有重复值。我用for weather in weatherDetail { print(weather.cityName) }。因此,这意味着原始循环包含错误。至少它给了我一个方向。