Swift - 数组不会在闭包中 .append(data) [英] Swift - Array won't .append(data) in closure

查看:34
本文介绍了Swift - 数组不会在闭包中 .append(data)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确定我错过了一些明显的东西.

I'm sure I miss something obvious.

使用 Parse Server 我想将请求中的一些数据填充到字典中.

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

如果我: print("Tableau image: \(bookImages)\n") 我的 var bookImages = [String?]() 中什么也没有,即使我在 coverString #2 里面有东西.

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

但是如果我 .append("foobar") 除了闭包之外的其他任何地方(尝试),我的字典不是空的.

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

为什么会有这种奇怪的魔法?

Why this strange magic ?

推荐答案

findObjectsInBackgroundWithBlock 是一个异步操作.

所以您的数组(.append 用于数组,而不是字典)可能已正确填充,但您正在查看它时还没有.

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.

如果将 print 语句放在闭包中,您将看到结果.

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

并且您还应该在那里重新加载 TableView,但将其重新分配到主线程.

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

示例:

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

}

这篇关于Swift - 数组不会在闭包中 .append(data)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆