我在 UIViewController 中有一个 TableView ,并从数据库加载数据。但是当我启动应用程序时,表是空的。只有当我单击表格时,数据才会出现。有人能告诉我我必须改变什么吗?这是我的代码:
#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
最佳答案
不喜欢
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];
});
}
关于ios - Objective-C:UIViewController 中的 TableView - 单击后仅加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38787382/