经过研究,我发现了 sigleton 可能对我有帮助,但我在理解它是如何工作时遇到了一些问题。 我需要两个类(class)相互沟通,这里有一个例子: 我有一个 tableView ,其中字段是动态的。 这是我在 viewController.h 文件中的代码:
-(void)ottieniMarche{
responseSimulate = [[NSArray alloc]initWithObjects:@"pollo",@"cane",@"gatto",@"verme",@"gallo",@"topo",@"canguro",@"elefante",@"giraffa" ,nil];
}
现在我必须在我的 mainTableView.m 广告上发送此信息,我实际使用的代码是这样的:
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
elementMainTableView = [[NSArray alloc]initWithObjects:@"aaa",@"bbb",@"ccc",@"ddd",@"eee",@"fff",@"ggg",@"hhh",@"iii" ,nil];
}
return self;
}
现在我必须使用responseSimulate 值更改elementMainTableView 值。我的意思是我的maintableView 的内容与我的responseSimulate 相同。
最佳答案
如果我正确理解你的问题,你想根据模型更改刷新 UITableView
的内容。
UITableView
需要一个符合 UITableViewDataSource
协议(protocol)的类来提供其行和部分数据。通常,这是一个 UITableViewController
,但并非必须如此。 UITableView
的数据源可以是您引用的其他类。在这种情况下,关键是当您更改数据时要求重新加载数据,即[tableView reloadData]
。
就您而言,如果您的 MainTableView
(我推断这实际上是 UITableViewController
子类...)符合 UITableViewDataSource
协议(protocol),那么您可以使用键值观察来解决问题,例如:(注意,此示例假设您使用的是 ARC。)
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if( !self ) return nil;
elementMainTableView = [[NSArray alloc] initWithObjects:@"aaa",@"bbb",@"ccc",nil];
[self addObserver:self forKeyPath:@"elementMainTableView" options:NSKeyValueObservingOptionNew context:NULL];
return self;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context;
{
if( [keyPath isEqualToString:@"elementMainTableview"] )
{
[[self tableView] reloadData];
}
}
这假设您将 elementMainTableView
公开为 MainTableView
上的属性。
现在,在另一个类(?ViewController)中你的方法:
-(void)ottieniMarche {
responseStimulate = [[NSArray alloc] initWithObjects:@"pollo",@"cane",@"gato",nil];
_mainTableViewController.elementMainTableView = responseStimulate;
}
为此,您需要 ViewController
来保留对 MainTableView
的引用,例如上面的_mainTableViewController
。
关于Objective-C:类之间如何通信?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9681223/