2013-03-20 5 views
-1

나는 탭 표시 줄이 있습니다. 첫 번째보기에는 login alertview가 필요하며 정상적으로 작동합니다. 다음 탭으로 전환하면 테이블보기가 나타납니다.iOS Reload Table Methods

다른 로그인 프로 시저와 함께 테이블 뷰 컨트롤러의 viewDidLoad 메서드에서 호출하는 메서드에서 JSON을 사용하여 온라인에서 데이터를 가져옵니다. 두 섹션을 원하고 각 섹션의 데이터는 데이터 구문 분석에서 얻은 속성 중 하나에 따라 다릅니다.

문제는 데이터가 구문 분석 될 때까지 테이블 뷰 메서드가 이미 완료되어 0 섹션과 0 행이 표시되고 데이터가 표시되지 않는다는 것입니다. 내 질문에, 거기에 방법을 섹션 메서드의 아니, 그냥 행을 메서드 및 cellForRowAtIndexPath 메서드를 다시로드하는 것입니다./

편집 : 내가 전체 테이블보기를 다시로드, 내가 로그인을 요청 무한 alertviews을 얻을

 #import "BooksViewController.h" 
    #import "Me.h" 
    #import "SBJson.h" 

    @interface BooksViewController() 

    @end 

    @implementation BooksViewController 

    @synthesize name = _name; 
    @synthesize ID = _id; 
    @synthesize extended = _extended; 
    @synthesize returned = _returned; 
    @synthesize Date = _date; 

    -(void) dealloc 
    { 
     self.name = nil; 
     self.ID = nil; 
     self.extended = nil; 
     self.returned = nil; 
     [super dealloc]; 
    } 

    - (id)initWithStyle:(UITableViewStyle)style 
    { 
     self = [super initWithStyle:style]; 
     if (self) { 

      BooksBorrowed = [[NSMutableArray alloc]init]; 
      BorrowedDates = [[NSMutableArray alloc]init]; 
      BorrowedIDs = [[NSMutableArray alloc]init]; 
      BorrowedExtensions = [[NSMutableArray alloc]init]; 
      BorrowedReturns = [[NSMutableArray alloc]init]; 

      /*message = [[UIAlertView alloc] initWithTitle:@"Please Login with your User       ID and Password" 
       message:nil 
       delegate:self 
       cancelButtonTitle:@"Cancel" 
       otherButtonTitles:@"Continue", nil]; 

       [message setAlertViewStyle:UIAlertViewStyleLoginAndPasswordInput];*/ 
      //book = [[BooksViewController alloc]init]; 
      me = [[Me alloc]init]; 
     } 
     return self; 
    } 

    - (void)MyBooks 
    { 
NSString *authFormatString = 
@"http://localhost:8888/Jineel_lib/bookBorrowed.php?uid=%d"; 

NSString *urlString = [NSString stringWithFormat:authFormatString, 1]; 

NSURL *url = [NSURL URLWithString:urlString]; 

NSString *contents = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil]; 

response1 = [contents JSONValue]; 
if(contents) 
{ 
    NSLog(@"contents : %@",contents); 
    BookName = [[NSString alloc]init]; 
    DateBorrowed = [[NSString alloc]init]; 
    BookID = [[NSString alloc]init]; 
    BookExtended = [[NSString alloc]init]; 
    BookReturned = [[NSString alloc]init]; 

    BookName = [response1 valueForKey:@"BookName"]; 
    BookID = [response1 valueForKey:@"BookID"]; 
    DateBorrowed = [response1 valueForKey:@"DateBorrowed"]; 
    BookExtended = [response1 valueForKey:@"Extended"]; 
    BookReturned = [response1 valueForKey:@"Returned"]; 

    [BooksBorrowed addObject:BookName]; 
    [BorrowedDates addObject:DateBorrowed]; 
    [BorrowedIDs addObject:BookID]; 
    [BorrowedReturns addObject:BookReturned]; 
    [BorrowedExtensions addObject:BookExtended]; 

    NSLog(@"Arrays are : %@, %@, %@, %@, %@", BooksBorrowed, BorrowedDates, BorrowedIDs, BorrowedReturns, BorrowedExtensions); 
     } 
    } 


    - (void)viewDidLoad 
    { 
     [super viewDidLoad]; 

     // Uncomment the following line to preserve selection between presentations. 
     // self.clearsSelectionOnViewWillAppear = NO; 

     // Uncomment the following line to display an Edit button in the navigation bar   for this view controller. 
     // self.navigationItem.rightBarButtonItem = self.editButtonItem; 
     [self MyBooks]; 
    } 

    - (void)didReceiveMemoryWarning 
    { 
[sup   er didReceiveMemoryWarning]; 
     // Dispose of any resources that can be recreated. 
    } 

    #pragma mark - Table view data source 

    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
    { 
     // Return the number of sections. 
     return 1; 
    } 

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(  (NSInteger)section 
    { 
     // Return the number of rows in the section. 
     NSLog(@"rows %d", [BooksBorrowed count]); 
     return [BooksBorrowed count]; 
    } 

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
    { 
     static NSString *CellIdentifier = @"Cell"; 
     UITableViewCell *cell = [tableView   dequeueReusableCellWithIdentifier:CellIdentifier]; 
     if (cell == nil) { 
      cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault   reuseIdentifier:CellIdentifier] autorelease]; 
     } 

        bookName = BooksBorrowed[0]; 

        cell.textLabel.text = bookName; 
        return cell; 
    } 

    @end 
+1

이있다 ** 절대적으로 아무것도 ** 모든 엑스 코드와 함께 할 수 있습니다. –

+0

모든 데이터가 구문 분석 될 때까지 기다린 다음 다시로드 하시겠습니까? –

+2

진심으로 나는 당신의 문제가 무엇인지 이해하지 못합니다. UITableView의 reloadData 메소드를 호출하면 호출 된 모든 델리게이트 메소드 (section의 n 개, section 및 cellForRowAtIndexPath의 행 수)가 표시됩니다. 그리고 테이블 뷰를 소유 한 뷰/뷰 컨트롤러의 메서드 (이 메서드들에서 직접 호출하지 않아야 함)는 –

답변

1

데이터를 가져 오는 작업이 백그라운드 스레드에서 수행되어야 UI가 차단되지 않습니다. 데이터를 가져온 후 테이블 뷰 데이터 원본이 업데이트되고 테이블 뷰가 다시로드됩니다. 이 작업은 주 스레드에서 수행해야합니다.

다음 코드는 생각을 보여 안 :

- (void)updateMyBooks 
{ 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
     // Fetch data on a background thread: 
     NSURL *url = ...; 
     NSString *contents = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil]; 
     if (contents) { 
      NSMutableArray *newBooksBorrowed = [NSMutableArray array]; 

      // ... Parse JSON response and add objects to newBooksBorrowed ... 

      dispatch_sync(dispatch_get_main_queue(), ^{ 
       // Update data source array and reload table view. 
       BooksBorrowed = newBooksBorrowed; 
       [self.tableView reloadData]; 
      }); 
     } 
    }); 
} 
+0

이 좋습니다. 고마워 ...이 방법을 어디에서 호출 할까? ViewDidLoad 또는? –

+0

이봐, 내가 테이블을 세우려고 할 때, 추락한다. 내가 잘못 가고있는 곳을 말해 줄 수 있니? cell.textLabel.text = [BooksBorrowed objectAtIndex : 0]; –

+0

@ user2176687 : 이것을 viewDidLoad에서 호출 할 수 있습니다. 충돌에 대한 오류 메시지가 있습니까? –

0

당신은 갈 2 가지 방법이있다.

현재 스레드에서 끝까지 구문 분석 할 때까지 기다리십시오.

-(void)aFunc { 
    //your job A 
    while (A is not finished) { 
     // If A job is finished, a flag should be set. and the flag can be a exit condition of this while loop 
     // This executes another run loop. 
     [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; 
} 

[yourTable reloadData]; 
} 

또는 특정 섹션 만로드하십시오.

– reloadRowsAtIndexPaths:withRowAnimation: 
– reloadSections:withRowAnimation: 
– reloadSectionIndexTitles 

EDIT :

다른 방법은 직렬 큐를 사용하여 GCD입니다. dispatch_sync()이면 블록이 대기열에 들어가고 블록이 실행될 때까지 함수가 반환되지 않습니다.

+0

모든 데이터가 구문 분석 될 때까지 기다렸다가 다시로드하려고합니다. 그것이 제가 염두에 두었던 것입니다. 어떻게 tableview 대리자의 특정 메서드를 호출합니까? [self reloadRowsAtIndexPaths : withRowAnimation : YES]? –

+0

편집 된 답변 확인 –

+0

나는 [self.tableview reloaddata]를 시도했지만, 내가 할 때보기가로드 된 방법을 호출하고 login alertview의 inifinite 루프로 끝납니다 :/ –