【问题标题】:Duplicate data in my tableview while using endless scroll使用无限滚动时在我的表格视图中重复数据
【发布时间】:2016-09-18 23:07:38
【问题描述】:

我正在使用这种方法在我的 tableview 中实现无限滚动:

- (void)scrollViewDidScroll:(UIScrollView *)scrollView_
{
CGFloat actualPosition = scrollView_.contentOffset.y ;
CGFloat contentHeight = scrollView_.contentSize.height - (700);
NSLog(@"table: %f", self.tableView.frame.size.height);
if (actualPosition >= contentHeight)
{  // self.articles = NULL;
    [self makeRequest:currentpage++];
    [self.articlesArray addObjectsFromArray:articles];
    [self.tableView reloadData];

}
}

我从这样的网络服务获取数据:

-(void)makeRequest:(int)page1{


NSString *urlString = [NSString
                       stringWithFormat:@"http://url/wp-json/wp/v2/posts?page=%d",(int) page1];

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];

NSData *theData = [NSURLConnection sendSynchronousRequest:request
                                        returningResponse:nil
                                                    error:nil];

self.articles = [NSJSONSerialization JSONObjectWithData:theData
                                                     options:NSJSONReadingMutableContainers
                                                       error:nil];

}

在我的视图控制器的 viewDidLoad 中如下:

- (void)viewDidLoad {
[super viewDidLoad];

self.articlesArray = [[NSMutableArray alloc] init];
 self.articles = [[NSMutableArray array]init];
currentpage = 0;
}

在显示新数据之前,我获得了两次数据。如何防止这种情况发生?

【问题讨论】:

    标签: ios objective-c json uitableview uiscrollview


    【解决方案1】:

    当发出这样的寻呼请求时,只需跟踪请求是否正在进行。在文件的界面中跟踪变量,例如:

    bool isLoadingMoreData = NO
    

    那么,当你提出请求时:

    -(void)makeRequest:(int)page1{
    
    if (self.isLoadingMoreData) {
        return
    }
    self.isLoadingMoreData = YES
    
    NSString *urlString = [NSString
                           stringWithFormat:@"http://url/wp-json/wp/v2/posts?page=%d",(int) page1];
    
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
    
    NSData *theData = [NSURLConnection sendSynchronousRequest:request
                                            returningResponse:nil
                                                        error:nil];
    
    self.articles = [NSJSONSerialization JSONObjectWithData:theData
                                                         options:NSJSONReadingMutableContainers
                                                           error:nil];
    
    self.isLoadingMoreData = NO
    
    }
    

    这是防止重复请求的简单方法

    【讨论】:

      猜你喜欢
      • 2012-05-13
      • 1970-01-01
      • 2017-11-30
      • 1970-01-01
      • 2013-12-30
      • 2012-02-25
      • 2012-07-15
      • 2016-10-12
      • 2017-09-15
      相关资源
      最近更新 更多