ViewDidLoad后NSMutableArray为空

时间:2016-08-19 07:20:26

标签: objective-c xcode uitableview nsmutablearray

这里没有在tableView中加载数据是我的描述。

  • 我正在尝试从API中添加对象,这些对象以JSON格式的数据响应我的NSMutableArray但它没有加载tableview。
  • 我可以看到数组设置正常但是在我尝试滚动tableview之前它没有加载到tableview中。

这太烦人了,无法弄清楚为什么请帮助我搞清楚。

这是我的代码 -

 - (void)viewDidLoad {

     [SVProgressHUD showWithStatus:@"Please wait ..."];


    //get the bookings
    [self getBookings];

    [super viewDidLoad];

    [self.tableView reloadData];
}
-(void) getBookings
{ 
    uid=@"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];
}

2 个答案:

答案 0 :(得分:0)

使用它可以帮助你

- (void)viewDidLoad {

    [SVProgressHUD showWithStatus:@"Please wait ..."];


    //get the bookings
    [self getBookings];

    [super viewDidLoad];
}

-(void) getBookings
{

    uid=@"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 :(得分:0)

编码约定:任何属性的支持变量都应以下划线开头。喜欢_bookingsList。如果您不遵循该连接,我们无法知道如果没有完整的源代码,其中bookingsList的分配将存储结果。