Reputation: 315
I'm using pull to refresh in my app for collection view but app is crashing with error.
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 2 beyond bounds for empty array'
I'm using asynchronous queue to get the data from server.
Following is my code to get the data from server and update ui on success:
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
}
);
}
Upvotes: 0
Views: 1204
Reputation: 2952
I think you should reload your collection view or tableview after calling refreshcontrol.endrefreshing. Like:-
@objc func refresh(sender:AnyObject) {
// Code to refresh table view
//Do all other API Calling stuff here
refreshControl.endRefreshing()
self.tableviewList?.reloadData()
}
It will work perfectly!! :)
Upvotes: 3
Reputation: 134
The problem is your taking the values from array without checking the size of array
Upvotes: 0
Reputation: 268
when performing pull to refresh . its default behaviour to reload table at that time your array becomes blank so it will be crash. so for this alloc your array after getting web service response.
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
});
there is no required to use this methodall time . it reduce app performance. because it waiting for Queue or main thread becomes free.
Upvotes: 0
Reputation: 1281
In your collection view datasource check if the array is empty , you are trying to access an empty array, use below code to check array is empty and return 0.
if (array == nil){
return 0;
}
Upvotes: 0
Reputation: 266
That's because the data in your data model is inconsistent with with the UITableView's date source methods returns.
Upvotes: 1