虽然可以在UIView draw(_ :)内读取数据,但当UIView图层设置为CATiledLayer时则无法。下面的代码(使用CATiledLayer时给出“线程4:EXC_BAD_ACCESS(代码= 1,地址= 0x7fcc95b1d170)”):

class Test2: UIView{
var points = [String]()

override init(frame: CGRect){
    super.init(frame: frame)

    let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("DB.sqlite")
    if sqlite3_open(fileURL.path, &db) == SQLITE_OK{
        print(fileURL.path)
    }
    else{
        print("error opening database")
    }
}
required init?(coder aDecoder: NSCoder){
    super.init(coder: aDecoder)
}

//Thread 4: EXC_BAD_ACCESS (code=1, address=0x7fcc95b1d170) when the following is used
//override class var layerClass: AnyClass{
//    return CATiledLayer.self
//}


func read(tile: String){
    var stmt:OpaquePointer?
    points = []
    let queryString = "SELECT * FROM Map WHERE tile = '\(tile)'"
    if sqlite3_prepare(db, queryString, -1, &stmt, nil) != SQLITE_OK{
        let errmsg = String(cString: sqlite3_errmsg(db)!)
        print("error preparing read: \(errmsg)")
        return
    }
    while(sqlite3_step(stmt) == SQLITE_ROW){
        points = String(cString: sqlite3_column_text(stmt, 2)).components(separatedBy: ",")
    }
}

override func draw(_ rect: CGRect){
    read(tile: "110_100")
     print(points)
}


}

最佳答案

我找到了答案。可能的问题是,当使用CATiledLayer时,“在一个或多个背景线程上调用了图层的draw(in :)方法”(https://developer.apple.com/documentation/quartzcore/catiledlayer),而SQLite“无法处理多线程情况”(https://www.yudiz.com/which-database-type-should-i-follow-in-my-ios-application

关于swift - UIView draw(_ :)中的SQLite3查询不适用于CATiledLayer,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51810174/

10-12 13:26