简体   繁体   English

首次加载ViewController时未加载Tableview

[英]Tableview not loading when viewcontroller is loaded for the first time

I am Using tableview with searchbar, json is fetching properly from server. 我正在将tableview与searchbar一起使用,json正在从服务器正确获取。 but data is not loading in my tableview when I open viewcontroller for the fist time, however when I type somthing in my searchbar data is visible and it is getting filtered, and then shown properly in my tableview. 但是当我第一次打开viewcontroller时,数据没有加载到我的表视图中,但是当我在搜索栏中键入东西时,数据是可见的并且已被过滤,然后在我的表视图中正确显示。 can anyone tell me whatcould be issues here? 谁能告诉我这里可能有什么问题? I want tableview to load entire json data when it is open fist time. 我希望tableview在打开时间时加载整个json数据。

here is my code 这是我的代码

    - (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];

}

Put [self.residentListTableView reloadData]; [self.residentListTableView reloadData]; inside NSURLSession completionHandler block. NSURLSession completionHandler块中。 Your current logic is wrong because of data is not loaded when you call [self.residentListTableView reloadData]; 您当前的逻辑是错误的,因为调用[self.residentListTableView reloadData];时未加载数据[self.residentListTableView reloadData]; . The NSURLSession task executed asynchronous and when you call [self.residentListTableView reloadData]; NSURLSession任务以异步方式执行,并且在您调用[self.residentListTableView reloadData];时执行[self.residentListTableView reloadData]; , the data is not available. ,数据不可用。

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];

you need to [self.residentListTableView reloadData]; 您需要[self.residentListTableView reloadData]; in your completion block (ie before the closing brace following NSLog(@"GGGGGGGGHHHHHHHH:%@",productArray); . 在您的完成代码块中(即NSLog(@"GGGGGGGGHHHHHHHH:%@",productArray);之后的NSLog(@"GGGGGGGGHHHHHHHH:%@",productArray);括号之前NSLog(@"GGGGGGGGHHHHHHHH:%@",productArray);

What's happening here is the block is executing asynchronously (AKA later when it gets a response back from the server). 这里发生的是该块异步执行(又是稍后从服务器返回响应时又执行)。 You can check this by putting a breakpoint in the completion block and one after the completion block. 您可以通过在完成块中放置一个断点,并在完成块之后放置一个断点来进行检查。 When you run the code you'll see that the breakpoint after the block gets hit before the one in the block, and that means that you are currently calling [self.residentListTableView reloadData] before you've got the data back from the server. 运行代码时,您会看到该块后的断点在该块中的断点之前被命中,这意味着您当前正在调用[self.residentListTableView reloadData]然后再从服务器取回数据。

one more thing. 还有一件事。 The block is also, likely, being executed on a background thread, so it is good practice to put this reloadData call on the main thread because it is updating UI, like so... 该块也可能在后台线程上执行,因此,最好将这个reloadData调用放在主线程上,因为它正在更新UI,就像这样...

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

Thanks @TMin and @nylohu, This worked for me. 感谢@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];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 NotificationCenter 在从视图控制器发布到另一个视图控制器时第一次不工作 - NotificationCenter is not working first time when it is posted from viewcontroller to another ViewController 首次加载iOS7 SDK时部分隐藏的tableview - tableview partially hidden first time loaded with iOS7 SDK 从第一次未处理的方案中加载 url - appdelegate vs viewcontroller - loading url from scheme not processing first time - appdelegate vs viewcontroller 在加载ViewController之前加载MapView - Loading MapView before ViewController is loaded 第二次加载viewcontroller时,UITableView reloadData无法正常工作 - UITableView reloadData not working when viewcontroller is loaded a 2nd time 第一次没有在iOS 10的tableview中加载图像,但是在滚动后? - Image not loading in tableview in iOS 10 on first time, but after scroll? iOS - ViewController中的第三个TableView没有加载nib - iOS - Third TableView in ViewController not loading nib Phonegap 3.5.0第一次加载页面时未加载本地javascript文件 - Phonegap 3.5.0 not loading local javascript files first time page is loaded 加载视图控制器后加载collectionview的imageviews - loading imageviews of collectionview after the viewcontroller is loaded 解析不加载tableview中的第一张图片 - parse not loading first images in tableview
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM