【问题标题】:Reading from an array before appending items to it (crash)在将项目附加到数组之前从数组中读取(崩溃)
【发布时间】:2015-10-16 09:28:47
【问题描述】:

在我设置的类初始化下:

var cardsCover = [PFFile]()

我有两个功能。其中之一从 Parse.com 获取数据并将其附加到数组中:

     let cards = PFQuery(className: "cards")
        cards.whereKey("category", equalTo: "Fruits")

        cards.findObjectsInBackgroundWithBlock { (cards: [PFObject]?, error: NSError?) -> Void in                
            if error == nil {
                for card in cards! {
                    self.cardsCover.append(card["cover"] as! PFFile)
                }
            } else {
                print("error")
            }
         }

第二个函数取自 cardsCover 数组并显示项目:

self.cardsCover[self.cardIndex].getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) -> Void in
        if imageData != nil {
             let image = UIImage(data: imageData!)
             let imageView = UIImageView(image: image!)
             contentView.addSubview(imageView)
        } else {
              print(error)
        }
 }

但是当我启动我的应用程序时,它首先尝试显示空数组中的图像,而不是将项目附加到数组中,然后再从中读取。所以,它崩溃了。

我在第二个函数的第一行设置断点,当我输入时:

po cardsCover

它返回0 elements。

我该如何解决这个问题并首先将项目附加到我的数组中,然后再从中读取它们?

【问题讨论】:

  • 你什么时候准确地调用你的第二段代码?
  • 这两个函数都在 viewDidLoad @Larme 中
  • 我的问题是,你什么时候做self.cardsCover[self.cardIndex].getDataInBackgroundWithBlock etc。例如,您可能希望在 for 循环之后调用此代码:for card in cards!{}。
  • @Larme 我没听懂你=/

标签: ios arrays swift asynchronous parse-platform


【解决方案1】:

首先,在从 Array 中获取元素时,请始终对数组大小进行安全检查以避免崩溃。

其次,您需要确保从cardsCover 读取数据的函数总是在调用数据设置函数后被调用。您在数据提取器中有一个完成块,您可以在其中触发数据提取器。您还可以实现delegate 回调或在数据下载完成后发布通知,以便之后开始使用数据。

【讨论】:

    【解决方案2】:

    我认为 getDataInBackgroundWithBlock 是异步 API(听起来像是在主队列之外运行),因此您需要调度到主队列。这是怎么做的

    if self.cardsCover.count > self.cardIndex {
        self.cardsCover[self.cardIndex].getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) -> Void in  
            dispatch_async(dispatch_get_main_queue()) {              
                if imageData != nil {
                    if let image = UIImage(data: imageData!){
                        let imageView = UIImageView(image: image!)
                        contentView.addSubview(imageView)
                    } else { print ("imageData can not be converted to image") }
                } else {
                    print("There was no imageData")
                }
            }
        }
    } else { print("cardIndex bigger than array count") }
    

    【讨论】:

    • 什么都没有。它再次打印fatal error: Array index out of range
    • 可能是这样,您正在另一个线程中获取数据,因此您可能想在完成后获取主线程
    • 我很久以前做过类似的项目,让我检查并编辑我的答案
    • 我已经更改了它,但没有再次更改。无论如何,它会崩溃
    • 也许 imageData 没有重新调整图像,用 if let 检查它
    猜你喜欢
    • 2019-01-01
    • 2020-10-30
    • 2014-02-20
    • 2023-03-27
    • 1970-01-01
    • 2023-03-21
    • 2013-09-05
    • 2017-09-28
    • 2011-04-07
    相关资源
    最近更新 更多