我正在尝试制作一个干净的MVC项目。 因此,使用NSNotificationCenter的观察者进行UIViews和ViewControllers之间的通信是好还是坏?
例如在CustomView.m中我创建了一个按钮:
- (void) makeSomeButton{
....
[bt addTarget:self action:@(buttonWasClicked) forControlEvents:UIControlEventTouchDragInside];
...
}
- (void) buttonWasClicked {
[[NSNotificationCenter defaultCenter] postNotificationName:@"buttonWasClicked" object:nil];
}
在viewCotroller.m中我在init部分添加观察者:
- (void)viewDidLoad { //
[self.view addSubview: [[CustomView alloc] initWithFrame ...]];
.....
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@(buttonWasClicked) name:@"buttonWasClicked" object:nil];
.....
}
then
- (void) buttonWasClicked{
// button was clicked in customView so do something
}
如果不正确,请解释在iOS应用中实施MVC模式的正确方法是什么?
答案 0 :(得分:2)
不,通知中心不应该在这种情况下使用。
我在这里使用的模式是委托。
在CustomView中,使用某种方法声明协议
标题顶部的:
@protocol CustomViewDelegate : NSObject
- (void)customViewDidSelectButton;
@end
在界面中。
@interface CustomView : NSObject
---
@property (nonatomic, weak) id <CustomViewDelegate> delegate;
---
@end
在实施中:
- (void) buttonWasClicked {
[self.delegate customViewDidSelectButton];
}
在View Controller Observing
中在实现文件中添加<CustomViewDelegate>
(同样放置TableViewDelegate等的地方..)
然后当您创建CustomView
集时,委托给自己。
实现委托方法:
- (void)customViewDidSelectButton {
// button was clicked in customView so do something
}