Objective-C:UIViewController中的TableView - 数据只需在单击后加载

时间:2016-08-05 10:48:03

标签: ios objective-c uiviewcontroller tableview

我在UIViewController中有一个表视图,我从数据库加载数据。但是当我启动应用程序时,表格是空的。只有当我点击表格时才会出现数据。有人能告诉我我必须改变什么吗?这是我的代码:

#import "DashboardViewController.h"
#import <UIKit/UIKit.h>

@interface DashboardViewController () 

@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *data;

@end

@implementation DashboardViewController


- (void)viewDidLoad {
    [super viewDidLoad];

}

-(void)viewWillAppear:(BOOL)animated{
    [self data]; // ???
}

- (NSMutableArray *)data {

    if(!_data){

        _data = [[NSMutableArray alloc] init];

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

        NSURLSession *session = [NSURLSession sharedSession];
        NSString *url = [NSString stringWithFormat:@"http://www.example.net/getData.php?user=%@", username];
        NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:url] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){

            NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            NSString *errorCode = [json valueForKey:@"error"];

            if([errorCode isEqualToString:@"e0"]){

                NSArray *myData = [json objectForKey:@"myData"];

                for (int i = 0; i < [myData count]; i++) {
                    [_data addObject:[myData objectAtIndex:i]];
                    [self.tableView reloadData];
                }

            }

        }];

        [dataTask resume];

    }

    return _data;

}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.data count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

    cell.textLabel.text = [[self.data objectAtIndex:indexPath.row] objectForKey:@"name"];

    return cell;
}

@end

1 个答案:

答案 0 :(得分:1)

不喜欢

for (int i = 0; i < [myData count]; i++) {
                [_data addObject:[myData objectAtIndex:i]];
                [self.tableView reloadData];
            }

喜欢

  

 for (int i = 0; i < [myData count]; i++) {
                [_data addObject:[myData objectAtIndex:i]];

            }

          if (_data.count>0)
         {
         dispatch_async(dispatch_get_main_queue(), ^(void){
        //Run UI Updates
          [self.tableView reloadData];
      });
        }