2012-06-04 5 views
51

파싱 된 데이터를 셀에로드하려고하는데 문제는 동기식으로 발생하고 데이터로드가 완료 될 때까지 UitableView가 표시되지 않습니다. performSelectorInBackground를 사용하여 문제를 해결하려고 시도했지만 이제는 스크롤을 시작할 때까지 데이터가 셀에로드되지 않습니다. 당신은 아마이 있어야,스크롤 할 때까지 데이터가 UITableView에서로드되지 않습니다.

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 

    [self performSelectorInBackground:@selector(fethchData) withObject:nil]; 


} 


- (void)viewDidUnload 
{ 
    [super viewDidUnload]; 
    // Release any retained subviews of the main view. 
self.listData = nil; 
    self.plot=nil; 
} 


-(void) fethchData 

{ 
    NSError *error = nil; 
    NSURL *url=[[NSURL alloc] initWithString:@"http://www.website.com/"]; 
    NSString *strin=[[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil]; 

    HTMLParser *parser = [[HTMLParser alloc] initWithString:strin error:&error]; 

    if (error) { 
     NSLog(@"Error: %@", error); 
     return; 
    } 

    listData =[[NSMutableArray alloc] init]; 
    plot=[[NSMutableArray alloc] init]; 

    HTMLNode *bodyNode = [parser body]; 
    NSArray *contentNodes = [bodyNode findChildTags:@"p"]; 


    for (HTMLNode *inputNode in contentNodes) { 
      [plot addObject:[[inputNode allContents] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];  
     } 


    NSArray *divNodes = [bodyNode findChildTags:@"h2"]; 

    for (HTMLNode *inputNode in divNodes) { 

      [listData addObject:[[inputNode allContents] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];   

     } 
    } 


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

    static NSString *CellIdentifier = @"Cell"; 
    //here you check for PreCreated cell. 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 
     cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 

    } 

    //Fill the cells... 


    cell.textLabel.text = [listData objectAtIndex:indexPath.row]; 
    cell.textLabel.font = [UIFont boldSystemFontOfSize:14]; 
    cell.textLabel.numberOfLines=6; 
    cell.textLabel.textColor=[UIColor colorWithHue:0.7 saturation:1 brightness:0.4 alpha:1]; 


    cell.detailTextLabel.text=[plot objectAtIndex:indexPath.row]; 
    cell.detailTextLabel.font=[UIFont systemFontOfSize:11]; 
    cell.detailTextLabel.numberOfLines=6; 

    return cell; 


} 
+0

만 볼 수 세포가로드, 나머지 세포가 될 것입니다

둘째, 난 당신이 같은 폐쇄 캡처 목록을 사용하여 강한 참조주기를 만들지 않도록하기로 생각 스크롤 한 후 표시됩니다. – rishi

답변

123

어딘가에 이를 넣습니다.

이 코드는 Apple의 GCD 기술을 사용하여 데이터로드 기능이 주 스레드에서 실행되도록합니다. Concurrency Programming Guide에 대한 자세한 내용을 읽어보십시오. (설명 부분에 설명하기에 꽤 큰 필드입니다.) 어쨌든 프로그램에서 드문 경우가 발생하기 때문에 잘 이해하지 못하는 경우에는 좋지 않습니다.

+0

감사합니다. 나는 급하게 주위를 움직 였고 데이터를로드하는 것이 다른 스레드에 있었기 때문에 내 reloadData도 있다는 것을 깨닫지 못했습니다. 저에게 돌아가서 사물을 분석하도록 도와 주셔서 감사합니다. – chadbag

+0

감사합니다. 이것은 내가 가지고있는 정말 짜증나는 버그를 방금 해결했습니다. –

+1

큰 도움! 감사합니다 – Greg

9

당신이 정말로해야 할 모든 당신이 백 엔드 데이터에 대한 업데이트를 가지고있는 시간이 있기 때문에

[tableView reloadData]; 

기적이 일어나고 호출한다 : 여기 내 코드입니다

-(void) updateTable 
{ 
    [tableView reloadData]; 
} 

추천하고 다운로드 전화에서 데이터를 추가 한 후 함수

[self performSelectorOnMainThread:@selector(updateTable) withObject:nil waitUntilDone:NO]; 
메인 스레드에 있지있는 동안

dispatch_async(dispatch_get_main_queue(), ^{ 
    [self.tableView reloadData]; 
}); 

이 GUI를 업데이트 를 호출의 문제를 해결 : 데이터가 성공적으로로드 된 후

+0

"unknown receiver tableView" – Benjamen

+0

코드는 예를 들어, 클래스 또는 뷰 레이아웃의 정확한 구조를 알지 못합니다. 중요한 점은 테이블 뷰에 대한 참조를 확보해야한다는 것입니다 (클래스가 UITableViewController의 인스턴스 또는 하위 클래스 인 경우 self.tableView가 있어야 함). 그리고 여기에'reloadData' 메소드를 호출하십시오. –

+0

UITabbleviewController ** self.tableView ** – LavaSlider

1

나는 똑같은 문제를 겪고있었습니다! 뷰 컨트롤러가 나타나기 전에 UITableView가 완전히 채워지 길 원했습니다. Envil의 게시물은 필자에게 필요한 정보를 제공했지만 솔루션은 결국 달라졌습니다.

다음은 내가 한 것입니다 (질문 작성자의 컨텍스트에 맞도록 개조되었습니다).

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    [self performSelectorInBackground:@selector(fethchData) withObject:nil]; 
} 

- (void)viewWillAppear { 
    [tableView reloadData]; 
} 
2

U [cell setNeedsDisplay]를 사용할 수 있습니다. 예를 들면 다음과 같습니다.

dispatch_async(dispatch_get_main_queue(), ^{ 
      [cell setNeedsDisplay]; 
      [cell.contentView addSubview:yourView]; 
     }); 
1

나는이 문제를 가지고 있었고, 나는 그것을 하루 종일 다루고있었습니다.

정적 셀을 사용하고 있고 reloadData가 잘못된로드를 일으키는 경우 표시되는 셀만 표시하고 다른 셀은 제거합니다. 내가 눈치 챘을 때, 올바르게로드 된 셀을 아래로 스크롤하면 (음수 값에서 y),이 코드를 작성 했으므로이 방법을 사용하지 않더라도 작동했습니다.

더 나은 해결책을 찾으면 촬영하십시오.빠른 3

-(void)reloadTableView{ 
     CGPoint point = self.tableSettings.tableView.contentOffset; 
     [self.tableSettings.tableView reloadData]; 

     [UIView animateWithDuration:.001f animations:^{ 
      [self.tableSettings.tableView setContentOffset:CGPointMake(point.x, -10)]; 
     } completion:^(BOOL finished) { 
      [UIView animateWithDuration:.001f animations:^{ 
       [self.tableSettings.tableView setContentOffset:point]; 
      } completion:^(BOOL finished) { 

      }]; 
     }]; 
} 
+0

이것은 나를 위해 일했습니다. 실제 문제를 파악한 경우 알려주십시오 –

13

:

DispatchQueue.main.async(execute: {() -> Void in 
       self.tableView.reloadData() 
      }) 

빠른 2의 :

dispatch_async(dispatch_get_main_queue(), {() -> Void in 
       self.tableView.reloadData() 
      }) 
+0

신속한 3 작품입니다! ... 감사합니다 –

+0

@MayPhyu 환영합니다 :) – Hamid

0

첫째, 반 해결 내 관련 문제. 나는 테이블 셀에서 이미지의 모서리를 둥글게하고 싶다. 디스패치 (Dispatch)는 비동기 적으로 일부 이미지 (모든 이미지가 아닌)의 문제를 해결했습니다. 어떤 아이디어?

에게
DispatchQueue.main.async(execute: { [weak weakSelf = self]() -> Void in 
      weakSelf!.tableView.reloadData() 
     }) 

참조 : https://developer.apple.com/library/prerelease/content/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html#//apple_ref/doc/uid/TP40014097-CH20-ID52

+0

이 문제는 DispatchQueue.main.async가 수정되었습니다 (실행 : {[weak weakCell = cell]() -> Void in weakCell! .imageView! .layer.cornerRadius = cell.imageView! .frame.width/4.0 weakCell! .imageView! .clipsToBounds = true }) – user3590685

관련 문제