在ViewDidLoad之后NSMutableArray为空
问题描述:
在tableView中加载的数据是我的描述。在ViewDidLoad之后NSMutableArray为空
- 我想从API中添加对象,它以JSON形式将数据反馈到NSMutableArray,但它不会使用tableview加载。
- 我可以看到数组设置好,但它不会加载到tableview,直到我尝试滚动tableview。
这是非常烦人的,无法弄清楚为什么善意帮我弄清楚。
这里是我的代码 -
- (void)viewDidLoad {
[SVProgressHUD showWithStatus:@"Please wait ..."];
//get the bookings
[self getBookings];
[super viewDidLoad];
[self.tableView reloadData];
}
-(void) getBookings
{
[email protected]"41";
bookingsList=[[NSMutableArray alloc] init];
NSString *urlAsString = [NSString stringWithFormat:@"http://www.webservice.com/cleaning/api/booking/show/%@/%d",uid,0];
NSURL *url = [[NSURL alloc] initWithString:urlAsString];
NSLog(@"%@", urlAsString);
[NSURLConnection sendAsynchronousRequest:[[NSURLRequest alloc] initWithURL:url] queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
NSLog(@"URL Session Task Failed: %@", [error localizedDescription]);
}
else {
NSArray *postsFromResponse = [NSJSONSerialization JSONObjectWithData: data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"Count %d", postsFromResponse.count);
NSLog(@"JSON: %@", postsFromResponse);
//remove all objects from array
[self.bookingsList removeAllObjects];
for (NSDictionary *attributes in postsFromResponse) {
booking *bk = [[booking alloc] init];
[bk setAddress:[attributes objectForKey:@"Address"]];
[bk setBookingId:[attributes objectForKey:@"BookingID"]];
[bk setServiceDate:[attributes objectForKey:@"ServiceDate"]];
[bk setClientName:[attributes objectForKey:@"ClientName"]];
[bk setStatus:[attributes objectForKey:@"Status"]];
[bk setServiceTime:[attributes objectForKey:@"ServiceTime"]];
[bk setPrice:[attributes objectForKey:@"Price"]];
[bk setCleanType:[attributes objectForKey:@"CleanType"]];
[bk setNumOfHours:[attributes objectForKey:@"NumOfHours"]];
//add to array
[self.bookingsList addObject:bk];
}
NSLog(@"Records found -%lu",(unsigned long)[bookingsList count]);
[self.tableView reloadData];
if(bookingsList.count==0)
{
UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"No Data Alert!"
message:@"No bookings found!" delegate:nil
cancelButtonTitle:@"OK" otherButtonTitles:nil];
//[alertView show];
[alertView performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:YES];
}
}
}];
[SVProgressHUD dismiss];
}
#pragma mark - TableView Delegate Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSLog(@"Total rows - %lu", (unsigned long)[self.bookingsList count]);
return [self.bookingsList count];
}
答
使用这个它会帮助你
- (void)viewDidLoad {
[SVProgressHUD showWithStatus:@"Please wait ..."];
//get the bookings
[self getBookings];
[super viewDidLoad];
}
-(void) getBookings
{
[email protected]"41";
bookingsList=[[NSMutableArray alloc] init];
NSString *urlAsString = [NSString stringWithFormat:@"http://www.webservice.com/cleaning/api/booking/show/%@/%d",uid,0];
NSURL *url = [[NSURL alloc] initWithString:urlAsString];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:urlAsString];
[request setHTTPMethod:GET_REQUEST];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *err)
{
if (error) {
NSLog(@"URL Session Task Failed: %@", [error localizedDescription]);
}
else {
NSArray *postsFromResponse = [NSJSONSerialization JSONObjectWithData: data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"Count %d", postsFromResponse.count);
NSLog(@"JSON: %@", postsFromResponse);
//remove all objects from array
[self.bookingsList removeAllObjects];
for (NSDictionary *attributes in postsFromResponse) {
booking *bk = [[booking alloc] init];
[bk setAddress:[attributes objectForKey:@"Address"]];
[bk setBookingId:[attributes objectForKey:@"BookingID"]];
[bk setServiceDate:[attributes objectForKey:@"ServiceDate"]];
[bk setClientName:[attributes objectForKey:@"ClientName"]];
[bk setStatus:[attributes objectForKey:@"Status"]];
[bk setServiceTime:[attributes objectForKey:@"ServiceTime"]];
[bk setPrice:[attributes objectForKey:@"Price"]];
[bk setCleanType:[attributes objectForKey:@"CleanType"]];
[bk setNumOfHours:[attributes objectForKey:@"NumOfHours"]];
//add to array
[self.bookingsList addObject:bk];
}
NSLog(@"Records found -%lu",(unsigned long)[bookingsList count]);
dispatch_async(dispatch_get_main_queue(),^{
[self.tableView reloadData];
});
if(bookingsList.count==0)
{
UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"No Data Alert!"
message:@"No bookings found!" delegate:nil
cancelButtonTitle:@"OK" otherButtonTitles:nil];
//[alertView show];
[alertView performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:YES];
}
}
}];
[task resume];
[SVProgressHUD dismiss];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSLog(@"Total rows - %lu", (unsigned long)[self.bookingsList count]);
return [self.bookingsList count];
}
+1
感谢您的建议,dispatch_async(dispatch_get_main_queue(),^ {self.tableView reloadData]; });似乎解决了这个问题。我必须替换[request setHTTPMethod:GET_REQUEST];与request.HTTPMethod = @“GET”; – Tajuddin
答
编码约定:背杂物任何属性都应该以下划线开头。像_bookingsList一样。如果你没有遵循这个连接,我们就不知道没有完整的源代码,在bookingsList的任务中将存储结果。
首先,您是否成功获得服务器的响应? – user3182143
是的,我确实得到了回应,并显示了JSON数据。正如我所说,它显示当我尝试滚动tableview。 – Tajuddin