我正在尝试制作一个干净的MVC项目。那么,使用NSNotificationCenter的观察者进行UIView和ViewController之间的通信是好事还是坏主意?
例如,在CustomView.mi中创建一个按钮:
- (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模式的正确方法是什么?
不,在这种情况下不应该使用通知中心。
我在这里使用的模式是委派。
在您的CustomView中,使用某种方法声明一个协议,
在标题顶部:
@protocol CustomViewDelegate : NSObject
- (void)customViewDidSelectButton;
@end
在界面中。
@interface CustomView : NSObject
---
@property (nonatomic, weak) id <CustomViewDelegate> delegate;
---
@end
在执行中:
- (void) buttonWasClicked {
[self.delegate customViewDidSelectButton];
}
在视图控制器中观察
在实现文件中添加<CustomViewDelegate>
(将TableViewDelegate等放置在同一位置。)
然后在创建CustomView
集合时将其委托给self。
实现委托方法:
- (void)customViewDidSelectButton {
// button was clicked in customView so do something
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句