0

While it is possible to read data inside UIView draw(_:), it is not when the UIView layer is set to be CATiledLayer. The code is below (giving "Thread 4: EXC_BAD_ACCESS (code=1, address=0x7fcc95b1d170)" when the CATiledLayer is used):

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

}

ckc
  • 345
  • 4
  • 12

1 Answers1

0

I found the answer. Probably the problem is that when the CATiledLayer is used, "the layer's draw(in:) method is called on one or more background threads" (https://developer.apple.com/documentation/quartzcore/catiledlayer), while SQLite "cannot handle multi threaded situation" (https://www.yudiz.com/which-database-type-should-i-follow-in-my-ios-application)

ckc
  • 345
  • 4
  • 12