I have built a JSON file that contains 14,000 airports and their names, timezones and other details. When appropriate I am making a data request to the JSON file and creating an array of Airports that I can search.
This runs, but is this the most efficient way to do this? It seems that building an array of 14,000 items every run will slow down the app. I want to query the database for an airport by code and return the other items associated with that object.
Thanks
Airport Object:
struct Airport: Codable {
var id: String
var name: String
var city: String
var country: String
var code: String
var icao: String
var timeZoneName: String
}
Data request code..
do {
let decoder = JSONDecoder()
let airports = try decoder.decode([Airport].self, from: data)
if let i = airports.firstIndex(where: { $0.icao == "KORD" }) {
print(airports[i].timeZoneName)
print(airports[i].name)
}
} catch {
print(error)
}
2
Answers
As mentioned in the comment, you should build a database for this. I think, CoreData is perfect for this.
On the first launch, you can load all your data into database, but later you only need to reach the db.
Add CoreData to existing project
import CoreData
and add the following code into AppDelegate:Create a new Entity
Write functions what you need
First I would write a manager for this like
I hope this helps 🙂
Did you actually measure it? 14,000 entries isn’t a lot. I remember writing an app that processed about 200,000 items on an iPhone 4s.
So measure it first. It might be fast enough, and the you leave it as it is. If it is close but not quite as fast as you want: instead of an array with 14,000 dictionaries, change your JSON file once into one dictionary with 8 keys if etc, each containing an array of 14,000 strings. So when you parse the JSON files the keys are not parsed 14,000 times, and you just create the array of Airport.
Make one function returning the array of airports. Start loading the data on s background thread asap. (All if you want to stay with JSON).