Swift - Array won't .append(data) in closure

2019-07-27 13:20发布

I'm sure I miss something obvious.

Using Parse Server I want to fill some data from a request into a dictionary.

query.findObjectsInBackgroundWithBlock { (books, error) in
            guard (books != nil) else {
                print(error)
                return
            }
            for book in books! {
                print("\n\n\(book)")  //#1 Got some book

                if let coverString = book["cover"] {
                    print("coverString OK : \(coverString)") //#2 got a valid String
                    self.bookImages.append(coverString as? String)
                } else {
                    print("coverString nil")
                    self.bookImages.append(nil)
                }
            }
        }

If I : print("Tableau image: \(bookImages)\n") I got nothing in my var bookImages = [String?]() even if I got something inside coverString #2.

but if I .append("foobar") anywhere else (to try) except in the closure my dictionary is not empty.

Why this strange magic ?

1条回答
霸刀☆藐视天下
2楼-- · 2019-07-27 13:51

findObjectsInBackgroundWithBlock is an asynchronous operation.

So your array (.append is for arrays, not dictionaries) is probably populated correctly but you are looking at it when it's not populated yet.

You will see the results if you put your print statements inside the closure.

And you should also reload the TableView there, but with redispatching it to the main thread.

Example:

query.findObjectsInBackgroundWithBlock { (books, error) in
    guard (books != nil) else {
        print(error)
        return
    }
    for book in books! {

        if let coverString = book["cover"] {
            print("coverString OK : \(coverString)")
            self.bookImages.append(coverString as? String)
        } else {
            print("coverString nil")
            self.bookImages.append(nil)
        }

        if let titleString = book["title"] {
            print("titleString OK : \(titleString)")
            self.bookTitle.append(titleString as? String)
        } else {
            print("titleString nil")
            self.bookTitle.append("No Title")
        }
    }

    print("Tableau image2: \(self.bookImages)\n")
    print("Tableau title2: \(self.bookTitle)\n")

    dispatch_async(dispatch_get_main_queue()) {
        self.collectionView?.reloadData()
    }

}
查看更多
登录 后发表回答