ios - 'RefreshControl' 上的“数组索引超出范围”

标签 ios swift uitableview

我有一个 TableView,我在其中从 api 获取数据。在获取/显示数据和分页/无限滚动方面一切正常。但是,当我尝试使用我的 RefreshControl 时,它崩溃并出现错误:

Array index out of range

 var theRefreshControl: UIRefreshControl!
 var results: [JSON]! = []
    // more stuff..

 func refresh(sender: AnyObject) {
        if isFirstLoad == false {
            self.results = []
            currentPage = 1
            getPosts()
        }
        self.theRefreshControl.endRefreshing()
    }

 override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell : PostCell = tableView.dequeueReusableCellWithIdentifier("PostCell") as! PostCell

    cell.delegate = self

    print(indexPath.row) // check below.

    let post = self.results![indexPath.row]    // 'array index out of range' here.

 }

为了获得有关错误的更多详细信息,我尝试添加 print(indexPath.row)。我收到的是,我在第一次加载时收到从 010 的信息,然后一刷新,它就变得很奇怪:

enter image description here

此外,当我点击 (i) 时:

{length = 2, path = 0 - 9}

有趣的是,完全相同的方法适用于我的其他 TableViewController,只有这个有问题。可能是什么问题?


func getPosts() {
    isLoading = true

Alamofire.request(.GET, link & params: ["page":"\(currentPage ?? 1)"])
  .responseJSON { response in

      // error checks

    if let data = json["data"].arrayValue as [JSON]? {

        self.lastPage = json["last_page"].int!
        self.currentPage = json["current_page"].int!

        if self.currentPage == 1 {
           self.results = data
           self.tableView.reloadData() 
        } else {                             
           var currentCount = self.results!.count;
           var indxesPath : [NSIndexPath] = [NSIndexPath]()

           for result in data {
             indxesPath.append(NSIndexPath(forRow:currentCount,inSection:0));
              self.results?.append(result)
              currentCount++
           }

     self.tableView.insertRowsAtIndexPaths(indxesPath, withRowAnimation: UITableViewRowAnimation.Bottom)                       
    }

编辑:请注意,我在刷新按钮中尝试了 results.removeAll() 以及 results.removeAll(keepCapacity: false) Action 函数,但没有运气。对于 `print(indexPath.row) - 我仍然得到相同的错误和相同的日志 - 在第一次加载时为 0 到 10,在刷新时,奇怪的是 6, 7, 8, [], 9

最佳答案

Swift 3.0 - 同样的问题,以与@mcclux 类似的方式解决,但少了一个步骤。

使用内置的 UIRefreshControl。 var refreshControl: UIRefreshControl!,然后在 viewDidLoad 中配置它:

    refreshControl = UIRefreshControl.init()
    refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
    refreshControl.addTarget(self, action: #selector(yourViewControllerName.yourFunctionToCallOnRefresh), for: UIControlEvents.valueChanged)
    tableView.addSubview(refreshControl)

然后您可以将您的代码包装在 cellForRowAt indexPath 中

if !self.refreshControl.isRefreshing { ... }

在经历了几个小时的崩溃后,它对我来说非常完美。希望这对您有所帮助!

关于ios - 'RefreshControl' 上的“数组索引超出范围”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34358239/

相关文章:

ios - UITableView 需要看起来像 Contacts with edit in place fields

ios - xCode:如何监控任何正在运行的第三方应用程序的 CPU 使用率

swift - 如何在SwiftUI的一个 View 上显示两个警报?

ios - 如何增加 UITableView 中自定义单元格的高度

ios - segue后返回原始 View

ios - 无法删除 Appcelerator Titanium for iOS 中的本地通知

Swift:通用协议(protocol)

ios - Swift Firebase 查询最多需要一分钟

ios - 在 TableView 上显示名称

iphone - 随着用户拉动,UITableView 中的标题不断增加