簡體   English   中英

檢索數據后如何實例化?

[英]How can I instantiate after retrieving data?

我正在從我的數據庫中檢索數據,並使用結構來處理該對象。 我需要訪問下面的newObj ,但圖像是nil 當我在從 data 到UIImage的轉換中打印圖像時,圖像存在,但是當我在.getDataInBackground下打印它時它為零。 我猜我必須將它放在塊中或在同步線程上運行它? 處理這個問題的正確方法是什么?

var pic = UIImage()
pic.getDataInBackground(block: { (data: Data?, error: Error?) in
    if(error == nil){
        let newPic = UIImage(data: data!)
        if(newPic != nil){
            pic = newPic!
            print("inside block \(pic)") //returns data
        }
    }else{
        print(error)
    }
})
print(pic) // returns 0

let newObj = Obj(name: "Bob", pic: pic) 

getDataInBackground閉包在后台線程上運行,需要一些時間,在調用閉包之前執行閉包之后的代碼,因此 pic 還沒有機會被初始化。

在您當前的代碼中,打印語句的順序應該是:

UIImage() // via `print(pic)`
inside block UIImage() // via `print("inside block \(pic)")`

你可能想在閉包的范圍內創建你的newObj ,如下所示:

pic.getDataInBackground(block: { (data: Data?, error: Error?) in
    // #3 0.25s
    if(error == nil){
        let newPic = UIImage(data: data!)
        if(newPic != nil){
            pic = newPic!
            print("inside block \(pic)")

            let newObj = Obj(name: "Bob", pic: pic)

            // pass the new object back to the main queue through 
            // a method
            DispatchQueue.main.async {
                collectObj(newObj)
            }

        }
    }
    else{
        print(error)
    }
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM