2017-03-22 8 views
0

私は検索バーでtableviewを使用しています.jsonはサーバーから正しくフェッチしています。私の検索ビューバーのデータが表示され、それがフィルタリングされて、私のテーブルビューに正しく表示されているにもかかわらず、私は一見のためにviewcontrollerを開くと、データが私のテーブルビューにロードされていません。 誰も私にここで何が問題になるのか教えてもらえますか? 開いているときにjsonデータ全体を読み込むようにtableviewします。 NSURLSession completionHandlerブロック内[self.residentListTableView reloadData];を入れ、ここviewcontrollerが最初に読み込まれたときにテーブルビューが読み込まれない

は私のコード

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

    [self customizeUI]; 

    NSString *savedUsername = [[NSUserDefaults standardUserDefaults] 
           stringForKey:@"username"]; 
    NSString *savedPassword = [[NSUserDefaults standardUserDefaults] 
           stringForKey:@"password"]; 

    isFiltered = NO; 

    self.residentSerachBar.delegate = self; 
    self.residentListTableView.delegate = self; 
    self.residentListTableView.dataSource = self; 

    filterdArray = [NSMutableArray new]; 
    productArray = [NSMutableArray new]; 

    NSURL *url = [NSURL URLWithString: @"XXXXX.json"]; 
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 

    [request setHTTPMethod:@"GET"]; 
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 

    NSString *authStr = [NSString stringWithFormat:@"%@:%@",savedUsername, savedPassword]; 
    NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding]; 
    NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodedStringWithOptions:0]]; 
    [request setValue:authValue forHTTPHeaderField:@"Authorization"]; 

    NSURLSession *session = [NSURLSession sharedSession]; 
    [[session dataTaskWithRequest:request 
       completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { 
        if (!error) { 
         NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; 

         productArray = [responseDictionary objectForKey:@"seniors"]; 

         NSLog(@"GGGGGGGGHHHHHHHH:%@",productArray); 
        } 
       }] resume]; 

    [self.residentListTableView reloadData]; 
} 

    - (void)customizeUI { 
    self.view.backgroundColor = [UIColor clearColor]; 
    self.baseResidentView.backgroundColor = [UIColor menyouSeniorsPopOverBackgroundColor]; 
    self.baseResidentView.layer.borderColor = [UIColor menyouKitchenLightGrayBorderColor].CGColor; 
    self.baseResidentView.layer.borderWidth = 2.0f; 


} 

    -(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{ 


    NSLog(@"HIIIIIIII"); 

    self.lableSelectResident.text = @""; 

    if(searchText.length == 0){ 

     isFiltered = NO; 
    }else{ 



     isFiltered = YES; 

       [filterdArray removeAllObjects]; 
     for(int i = 0; i < [productArray count]; i++){ 
      NSRange textRange; 
      textRange =[[[[productArray objectAtIndex:i] objectForKey:@"senior_name"] lowercaseString] rangeOfString:searchText options:NSCaseInsensitiveSearch]; 
      //I wasn't sure which objectForKey: string you were looking for, just replace the one you want to filter. 
      if(textRange.location != NSNotFound) 
      { 

       [filterdArray addObject:[productArray objectAtIndex:i]]; 

       NSLog(@"filterdArrayyyyyyyy:%@",filterdArray); 

      } 
     }    
    } 

    [self.residentListTableView reloadData]; 
} 

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ 

    return 1; 

} 

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ 

    if(isFiltered){ 

     return [filterdArray count]; 

    } 

    return [productArray count]; 

} 

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

    NSLog(@"LLLLLLLLLLLLLLL"); 

    static NSString *cellIdentifier = @"ResidentListTableViewCell"; 

    ResidentListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath]; 


    if(!cell){ 

     // cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; 
     cell = [[ResidentListTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; 

    } 

    if(!isFiltered){ 

    NSDictionary *productDictionary = [productArray objectAtIndex:indexPath.row]; 
     cell.residentNameLabel.text = [productDictionary objectForKey:@"senior_name"]; 

     if([productDictionary objectForKey:@"room_no"] == [NSNull null]){ 
      NSLog(@"CCCCCCC222222"); 
      cell.residentRoomIdLabel.text = @""; 

     }else{ 
      int room_no = [[productDictionary objectForKey:@"room_no"] intValue]; 
      cell.residentRoomIdLabel.text = [NSString stringWithFormat:@"%d", room_no];; 
     } 

     int rId = [[productDictionary objectForKey:@"id"] intValue]; 
     cell.residentIdLabel.text = [NSString stringWithFormat:@"%d", rId];    
    } 

    else{ 

      NSDictionary *productDictionary = [filterdArray objectAtIndex:indexPath.row]; 

     cell.residentNameLabel.text = [productDictionary objectForKey:@"senior_name"]; 

     if([productDictionary objectForKey:@"room_no"] == [NSNull null]){ 
      NSLog(@"CCCCCCC222222"); 
      cell.residentRoomIdLabel.text = @""; 

     }else{ 
      int room_no = [[productDictionary objectForKey:@"room_no"] intValue]; 
      cell.residentRoomIdLabel.text = [NSString stringWithFormat:@"%d", room_no];; 
     } 

     int rId = [[productDictionary objectForKey:@"id"] intValue]; 
     cell.residentIdLabel.text = [NSString stringWithFormat:@"%d", rId]; 
    } 

      return cell; 
} 

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ 

     ResidentListTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 

    self.lableSelectResident.text = cell.residentNameLabel.text; 

    self.residentId = cell.residentIdLabel.text; 
    self.residentRoomNo = cell.residentRoomIdLabel.text; 

    self.residentSerachBar.text = cell.residentNameLabel.text; 

    [self.view endEditing:YES]; 

} 

答えて

0

です。 [self.residentListTableView reloadData];を呼び出すとデータがロードされないため、現在のロジックが間違っています。 NSURLSessionタスクが非同期で実行され、[self.residentListTableView reloadData];を呼び出すと、データは使用できません。あなたはすなわちNSLog(@"GGGGGGGGHHHHHHHH:%@",productArray);以下の閉じ括弧の前に(あなたの完了ブロックに[self.residentListTableView reloadData];する必要があります。

ここで何が起こっている

NSURLSession *session = [NSURLSession sharedSession]; 
[[session dataTaskWithRequest:request 
      completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { 
       if (!error) { 
        NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; 
        productArray = [responseDictionary objectForKey:@"seniors"]; 
        NSLog(@"GGGGGGGGHHHHHHHH:%@",productArray); 
       } 
      }] resume]; 
+0

ありがとうございます@nynohu。私は以下のコードを解決しました。 – Shelby

0

は、それが戻ってサーバーからの応答を取得する際のブロック)がAKA後に(非同期的に実行されていますこれを確認するには、コンプリートブロックとコンプリートブロックの後にブレークポイントを置くことで確認できます。コードを実行すると、ブロック内のブレークポイントがブレークポイントより前にヒットしたことがわかります。サーバーからデータを取得する前に現在[self.residentListTableView reloadData]と呼び出しています。

もう1つ。 ...ブロックはおそらく、バックグラウンドスレッドで実行され、またあるので、それはそうのように、UIを更新しているので、メインスレッド上でこのreloadDataコールを置くことをお勧めし

dispatch_async(dispatch_get_main_queue(), 
^{ 
    [self.residentListTableView reloadData]; 
}); 
+0

ありがとうございました – Shelby

+0

ここに進捗バーを設定し、データがロードされた後にそれを却下する方法を教えてください。 – Shelby

+0

私はHUDを使ってそれを完成させました – Shelby

0

おかげ@TMinと@nylohu、 これは私のために働いた。

NSURLSession *session = [NSURLSession sharedSession]; 
[[session dataTaskWithRequest:request 
      completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { 
       if (!error) { 
        NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; 


        productArray = [responseDictionary objectForKey:@"seniors"]; 


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



       } 
      } 
    ] resume]; 
+0

また、ブロックがあるので、弱い自己/強い人の踊りをするべきです。 [link](https://dhoerl.wordpress.com/2013/04/23/i-finally-figured-out-weakself-and-strongself/) - > –

関連する問題