【问题标题】:Accessing Data Outside of Closure访问闭包之外的数据
【发布时间】:2015-07-18 02:07:38
【问题描述】:

我的班级中有一个数组,我试图将其填充到闭包中。但是,当我尝试访问/打印数组内容时,它似乎在闭包之外是空的。如何存储数据以供在闭包之外使用?

for index in 0..<6 {
        let picNumber = index + 1
        if let pica = currentuser.objectForKey("pic\(picNumber)") as? PFFile {
            pica.getDataInBackgroundWithBlock({ (data:NSData!, error:NSError!) -> Void in
                if error == nil {
                    self.pic1 = UIImage(data: data)
                    var imageS = scaleImage(self.pic1!, and: 200)
                    self.imagesForSection0.append(imageS)
                }
            })
            println(self.imagesForSection0)
        }
    }

【问题讨论】:

    标签: ios swift closures


    【解决方案1】:

    闭包外不为空

    getDataInBackgroundWithBlock方法是async,表示它会先返回。所以,你在print函数中什么都看不到。

    文档

    如果可用,则从缓存中异步获取数据或从网络中获取其内容。

    编辑

    for index in 0..<6 {
        let picNumber = index + 1
        if let pica = currentuser.objectForKey("pic\(picNumber)") as? PFFile {
            pica.getDataInBackgroundWithBlock({ (data:NSData!, error:NSError!) -> Void in
                if error == nil {
                    self.pic1 = UIImage(data: data)
                    var imageS = scaleImage(self.pic1!, and: 200)
                    self.imagesForSection0.append(imageS)
                }
            println(self.imagesForSection0)
            //Then call reload data
            })
        }
    }
    

    【讨论】:

    • 感谢您的帮助。仍然有点困惑,self.imagesForSection0 数组在文件的其他部分就像是空的一样。它应该在集合视图中显示检索到的图像,但它显示为空白。我应该使用其他方法吗?
    • 你应该把println函数放在闭包里面,数组改变后调用reloaddata
    • 啊完美。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-28
    • 2017-10-05
    • 1970-01-01
    相关资源
    最近更新 更多