【发布时间】:2019-12-28 14:00:13
【问题描述】:
我正在尝试加快我的应用程序的速度,不幸的是,目前它在使用 Swift Ui 执行某些搜索和数据列表时非常缓慢。
首先我有一个描述我的对象机场的数据模型,称为 AirportModel
import Foundation
class AirportModel : Identifiable , Codable{
var aptICAO : String
var aptName : String
var aptCity : String
var aptCountry :String
var aptIATA : String
init(aptICAO: String, aptName: String, aptCity: String, aptCountry: String, aptIATA: String) {
self.aptICAO = aptICAO
self.aptName = aptName
self.aptCity = aptCity
self.aptCountry = aptCountry
self.aptIATA = aptIATA
}
}
我有一个本地文件 apt.json,其中包含我机场的所有数据信息(我从网上下载了这个 json,里面大约有 29000 个机场)
所以当我第一次运行应用程序时,使用以下函数,我创建并保存了 AirportModel 类型的 airportVector。
func openfilejson (fileName : String) {
if let path = Bundle.main.path(forResource: fileName, ofType: "json") {
do {
let fileUrl = URL(fileURLWithPath: path)
let datafile = try Data(contentsOf: fileUrl,options: .mappedIfSafe)
let json = JSON(data:datafile)
objectWillChange.send()
for (key,_) in json {
let airport = AirportModel(aptICAO: "", aptName: "", aptCity: "", aptCountry: "", aptIATA: "")
airport.aptName = json[key]["name"].stringValue
airport.aptCity = json[key]["city"].stringValue
airport.aptCountry = json[key]["country"].stringValue
airport.aptIATA = json[key]["iata"].stringValue
airport.aptICAO = json[key].stringValue
airportVector.append(airport)
}
debugPrint("nel vettore airport Vector ci sono \(airportVector.count) aeroporti")
save2() // to save airport vector in the plistfile
debugPrint("SALVATO IN MEMORIA ")
} catch {
print("ERRORE OPEN FILE AEROPORTI")
}
}
}
所有,这个工作正常,一旦应用程序第一次是 ru,就会创建内部有 29000 个机场的向量。
现在是大问题。
在一个视图中,我尝试使用 SwiftUI 和 searchBar 来列出这个机场。
问题是,由于要打开的数据量很大,当我用列表加载视图时;数据需要很长时间才能列出,而且当我吃午饭时,搜索一切都卡住了!
知道如何处理或加速如此大量的数据,以避免应用卡在加载以下视图!
import SwiftUI
struct ContentView: View {
@ObservedObject var dm: DataManager
@State private var searchTerm : String = ""
var body: some View {
VStack {
Text("List")
SearchBar(text: $searchTerm).shadow(radius: 10)
List(dm.airportVector.filter{
$0.aptCity.localizedCaseInsensitiveContains(searchTerm)
|| $0.aptName.localizedCaseInsensitiveContains(searchTerm)
}){ item in
HStack {
Text(item.aptICAO).bold().font(Font.system(size:20)).frame(width: 90, height: 10)
//
Text(item.aptName).font(Font.system(size: 15))
Spacer()
VStack(alignment: .leading) {
Text(item.aptCity).font(Font.system(size: 10)).font(.subheadline)
Spacer()
Text(item.aptCountry).font(Font.system(size: 10))
}
}
}
}
}
}
提前致谢。 达米亚诺
【问题讨论】:
标签: arrays json filter model swiftui