我正在从另一个类调用我的 TableViewController 类中的一个方法。
要调用显示 tableview 的方法,我这样做:
TableViewController *tableVC = [[TableViewController alloc]init];
[tableVC setTableViewContent];
然后在TableViewController.h中
@interface TableViewController : UITableViewController <UITableViewDelegate, UITableViewDataSource>
{
NSMutableArray *nameArray;
}
-(void)setTableViewContent;
@property (nonatomic, strong) IBOutlet UITableView *tableView;
@end
TableViewController.m
@implementation TableViewController
@synthesize tableView;
- (void)viewDidLoad
{
nameArray = [[NSMutableArray alloc]init];
[super viewDidLoad];
}
-(void)setTableViewContent{
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
for(int i=0;i< [appDelegate.businessArray count];i++)
{
NSDictionary *businessDict = [[appDelegate.businessArray objectAtIndex:i] valueForKey:@"location"];
nameArray = [appDelegate.businessArray valueForKey:@"name"];
}
NSLog(@"%@", nameArray);
NSLog(@"tableview: %@", tableView);
// here tableview returns null
[tableView reloadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [nameArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"updating tableview...");
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
cell.textLabel.text = [nameArray objectAtIndex:indexPath.row];
return cell;
}
出于某种原因,当我尝试记录 TableView 时,它返回 null,因此 ReloadData 不起作用。代理和数据源在 IB 中正确连接,并且有一个 tableView 的引用导出。
知道这里发生了什么吗?提前致谢
最佳答案
如果您将 TableView Controller 添加到容器 View ,那么您可以在 prepareForSegue 中获取对该 Controller 的引用。对于容器 View 中的 Controller ,prepareForSegue 将在父 Controller 的 viewDidLoad 之前调用,因此您无需执行任何操作即可调用它。在我下面的示例中,我将 segue 称为“TableEmbed”——您需要在 IB 中为 segue 提供该标识符。
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if([segue.identifier isEqualToString:@"TableEmbed"]) {
TableViewController *tableVC = (TableViewController *)segue.destinationViewController;
[tableVC setTableViewContent];
}
}
请注意 prepareForSegue:sender: 在调用任一 Controller 的 viewDidLoad 之前被调用,因此您应该将数组的初始化移动到 setTableViewContent,并且您的 reloadTable 应该进入 viewDidLoad。
顺便说一句,我不清楚您为什么要从其他类调用 setTableContent。为什么不将该方法中的所有代码移动到 TableView Controller 的 viewDidLoad 方法中?
关于ios - UITableView 的 ReloadData 不起作用; tableView 在记录时返回 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17690708/