Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pull-to-refresh modifies array value?

I'm working on a pull-to-refresh on iOS with Swift.
I have an array with city names, cityNames = ["Chicago", "New York City"]
I implemented a pull-to-refresh to fetch temperature data from the internet. So every time I trigger the pull-to-refresh, it will go to the internet and get the temperature for each city in the cityNames array.
Here is the code for pull-to-refresh

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()
}

In the code above, weatherDetail is a array of model(I'm not sure how to phrase this, but Weather is a model, which contains city names, temperature, sun rise time, high/low temperature.
forwardGeocoding is a function that get the geo coordination for a city then sends a request to get the weather data for that city.
The pull-to-refresh works, the issue I'm encountering is, for the first 2,3 times when I pull, it works with no problem. But as I pull more times, the array will suddenly change to cityNames = ["Chicago", "Chicago"]
Thank you for your help, please let me know if you need more information.
UPDATE:
I removed weatherDetail.removeAll(), try to just append the same data to the array. After the refresh, it prints out "Chicago", "New York City", "Chicago", "Chicago". If I refresh it more times, it prints out something like "Chicago", "New York City", "Chicago", "Chicago", "Chicago", "Chicago"

like image 405
f_qi Avatar asked Apr 03 '16 19:04

f_qi


2 Answers

Is forwardGeocoding synchronous? When does weatherDetail get set/updated?

It looks to me like you have some sort of synchronicity issue going on here, probably exacerbated by latency.

like image 186
Michael Avatar answered Oct 13 '22 23:10

Michael


Using enumerate() and append() to do this is not a good approach ,there is a more elegance and error-proof way to achieve this:

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

Or just write:

let cityNames:[String] = weatherDetail.map { $0.cityName }
like image 31
wj2061 Avatar answered Oct 13 '22 23:10

wj2061