![](/img/trans.png)
[英]NotificationCenter is not working first time when it is posted from viewcontroller to another ViewController
[英]Tableview not loading when viewcontroller is loaded for the first time
我正在將tableview與searchbar一起使用,json正在從服務器正確獲取。 但是當我第一次打開viewcontroller時,數據沒有加載到我的表視圖中,但是當我在搜索欄中鍵入東西時,數據是可見的並且已被過濾,然后在我的表視圖中正確顯示。 誰能告訴我這里可能有什么問題? 我希望tableview在打開時間時加載整個json數據。
這是我的代碼
- (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];
}
把[self.residentListTableView reloadData];
在NSURLSession completionHandler
塊中。 您當前的邏輯是錯誤的,因為調用[self.residentListTableView reloadData];
時未加載數據[self.residentListTableView reloadData];
。 NSURLSession任務以異步方式執行,並且在您調用[self.residentListTableView reloadData];
時執行[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];
您需要[self.residentListTableView reloadData];
在您的完成代碼塊中(即NSLog(@"GGGGGGGGHHHHHHHH:%@",productArray);
之后的NSLog(@"GGGGGGGGHHHHHHHH:%@",productArray);
括號之前NSLog(@"GGGGGGGGHHHHHHHH:%@",productArray);
這里發生的是該塊異步執行(又是稍后從服務器返回響應時又執行)。 您可以通過在完成塊中放置一個斷點,並在完成塊之后放置一個斷點來進行檢查。 運行代碼時,您會看到該塊后的斷點在該塊中的斷點之前被命中,這意味着您當前正在調用[self.residentListTableView reloadData]
然后再從服務器取回數據。
還有一件事。 該塊也可能在后台線程上執行,因此,最好將這個reloadData調用放在主線程上,因為它正在更新UI,就像這樣...
dispatch_async(dispatch_get_main_queue(),
^{
[self.residentListTableView reloadData];
});
感謝@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.