拉动刷新崩溃ios app

时间:2014-03-25 10:27:16

标签: ios objective-c uicollectionview pull-to-refresh

我在我的应用程序中使用pull来刷新集合视图但是app崩溃了。

*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 2 beyond bounds for empty array'

我正在使用异步队列从服务器获取数据。

以下是我从服务器获取数据并在成功时更新ui的代码:

     refreshControl = [[UIRefreshControl alloc] init];
     [refreshControl addTarget:self action:@selector(startRefresh:)
           forControlEvents:UIControlEventValueChanged];

- (void)startRefresh:(UIRefreshControl *)refreshcontrol
{
    dispatch_queue_t fetchQueue = dispatch_queue_create("fetch Queue", NULL);

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
     //webservice call which on success post notification
    });
}


- (void)onSuccess:(NSNotification *)success { //notification after success of webservice
    [storyCollectionView setHidden:NO];
    NSLog(@"fun:%s", __func__);

    dispatch_async(dispatch_get_main_queue(), ^{//in the main queue i'm ending refresing
        if ([refreshControl isRefreshing]) {
        [refreshControl endRefreshing];
        } 

    [CollectionView reloadData];// reloading collection view
    }
                   );

  }

5 个答案:

答案 0 :(得分:3)

我认为您应该在调用 refreshcontrol.endrefreshing 后重新加载集合视图或表格视图。 像:-

@objc func refresh(sender:AnyObject) {
        // Code to refresh table view
        //Do all other API Calling stuff here
        refreshControl.endRefreshing()
        self.tableviewList?.reloadData()
    }

它将完美运行!! :)

答案 1 :(得分:1)

这是因为数据模型中的数据与UITableView的日期源方法返回不一致。

答案 2 :(得分:0)

在你的集合视图中,数据源检查数组是否为空,你试图访问一个空数组,使用下面的代码检查数组是否为空并返回0。

if (array == nil){
   return 0;
}

答案 3 :(得分:0)

执行pull刷新时。它的默认行为是重新加载表,那时你的数组变成空白,所以它会崩溃。所以为此在获得Web服务响应后分配您的数组。

dispatch_queue_t fetchQueue = dispatch_queue_create("fetch Queue", NULL);

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
 //webservice call which on success post notification
});

没有必要使用此方法。它会降低应用性能。因为它等待队列或主线程变得免费。

答案 4 :(得分:0)

问题是你从数组中获取值而不检查数组的大小

相关问题