我正在使用 UISplitviewController 并尝试将项目添加到 TableView 。
现在我有两种方法
创建一个按钮并添加它:
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(insertNewObject:)]; self.navigationItem.rightBarButtonItem = addButton;
此代码在单击按钮时运行:
- (void)insertNewObject:(id)sender {
if (!self.objects) {
self.objects = [[NSMutableArray alloc] init];
}
[self.objects insertObject:[NSDate date] atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
并向 TableView 添加一个项目:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
NSString *object = self.objects[indexPath.row];
cell.textLabel.text = [object description];
return cell;
}
这种方式可行。
这就是我想要做的:
- (void)GetRequest
{
if (!self.objects) {
self.objects = [[NSMutableArray alloc] init];
}
[self.objects insertObject:[NSDate date] atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
但这不会更新 TableView 。我添加了一个断点,当我使用我添加的按钮时,它进入 TableView ,使用它没有的方法,我通过 [MasterController GetRequest];
我做错了什么?
我正在从另一个 Controller 调用 GetRequest。
这就是 MasterController 的定义方式:
@interface DetailController ()
{
MasterController *MasterController;
}
DetailController.m:
#import "MasterController.h"
@interface DetailController ()
{
MasterController *MasterController;
}
@end
@implementation DetailController
-(void)viewDidLoad {
MasterController = [[MasterController alloc]init];
}
[MasterController GetRequest];
MasterController.m:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
NSString *object = self.objects[indexPath.row];
cell.textLabel.text = [object description];
return cell;
}
- (void)GetRequest
{
if (!self.objects) {
self.objects = [[NSMutableArray alloc] init];
}
[self.objects insertObject:[NSDate date] atIndex:0];
[self.tableView reloadData];
}
最佳答案
正如我所怀疑的,通过这一行 MasterController = [[MasterController alloc]init]
,您正在创建一个与您在屏幕上看到的实例无关的新实例。您需要获得对 Split View Controller 中已有的主 Controller 的引用。从详细 View Controller 中,您可以像这样获取,
MasterController = self.splitViewController.viewControllers.firstObject;
split view controller 有一个 viewControllers 属性,index 0 的是 master,index 1 的是 detail。顺便说一句,您应该以较低级别的字母开始您的 ivars 和方法名称。
关于ios - UITableViewController 通过方法添加项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29971827/