处理异步(Swift)

时间:2017-12-06 19:13:07

标签: ios arrays swift concurrency nsurlsession

我目前正在制作应用,但我遇到了异步问题。在应用程序中多次我必须从站点加载电影对象,将它们放在一个数组中,然后使用completionHandlers将视图控制器的数组定义到这个电影数组。在两种不同但相似的情况下,这是错误的:

  1. 这些电影对象需要在UICollectionView中显示,但是在数组中有任何内容之前调用numberOfItemsInSection会导致应用程序因索引超出范围错误而崩溃。该数组是一个数组数组(每个UITableViewCell的电影对象数组)

  2. 根据我要显示的流派,我从网站上加载电影对象。这些类型也从站点加载,以保持代码灵活变化。然后将类型保存在词典中。当我需要使用流派来加载电影时,类型数组仍然是空的。

  3. 关于这两者的最佳方法是什么?为什么?

    注意: 是的我知道 didSet 但是我需要行号来知道使用哪个键然后我可以加载这些电影对象数组。

    修改 一些代码可能会澄清情况

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    
            let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell
    
            //The moved this method to viewDidLoad() but it isn't done in time
            //Added this hear so you guys get an idea where genres come from
    
            getCategories(completionHandler: { genres in
                self.genres = genres
            })
    
            // The code crashes when I want to perform this method                      
            // because the genres array is still empty here, 
            // I don't know how to do it otherwise because I need   
            // indexPath.row to know which commando to use to load the 
            // film objects of a certain genre (the one that is related to this row)
    
            test(ID: genres[currentlyUsedGenres[indexPath.row]]!, completionHandler: { loadedMovies in
                self.loadedList.append(loadedMovies)
            })
    
            cell.selectionStyle = .none
            cell.movieLabel.setTitle(listNames[indexPath.item], for: .normal)
    
            cell.button.tag = indexPath.row
            cell.movieLabel.tag = indexPath.row
            return cell
    
    }
    

0 个答案:

没有答案
相关问题