在 iOS 应用程序中实现 MVC 模式的正确方法是什么?
What is the proper way to implement MVC pattern in iOS app?
我正在尝试创建一个干净的 MVC 项目。
那么在 UIViews 和 ViewControllers 之间使用 NSNotificationCenter 的观察者进行通信是好是坏?
例如在 CustomView.m 我做了一个按钮:
- (void) makeSomeButton{
....
[bt addTarget:self action:@(buttonWasClicked) forControlEvents:UIControlEventTouchDragInside];
...
}
- (void) buttonWasClicked {
[[NSNotificationCenter defaultCenter] postNotificationName:@"buttonWasClicked" object:nil];
}
并且在 viewCotroller.m 中,我在初始化部分添加了观察者:
- (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 中,使用某种方法声明一个协议,
在您的 header 顶部:
@protocol CustomViewDelegate : NSObject
- (void)customViewDidSelectButton;
@end
在界面中。
@interface CustomView : NSObject
---
@property (nonatomic, weak) id <CustomViewDelegate> delegate;
---
@end
实施中:
- (void) buttonWasClicked {
[self.delegate customViewDidSelectButton];
}
在视图控制器中观察
在实现文件中添加 <CustomViewDelegate>
(与放置 TableViewDelegate 等的位置相同)
然后当您创建 CustomView
集时,它会委托给自己。
实现委托方法:
- (void)customViewDidSelectButton {
// button was clicked in customView so do something
}
我正在尝试创建一个干净的 MVC 项目。 那么在 UIViews 和 ViewControllers 之间使用 NSNotificationCenter 的观察者进行通信是好是坏?
例如在 CustomView.m 我做了一个按钮:
- (void) makeSomeButton{
....
[bt addTarget:self action:@(buttonWasClicked) forControlEvents:UIControlEventTouchDragInside];
...
}
- (void) buttonWasClicked {
[[NSNotificationCenter defaultCenter] postNotificationName:@"buttonWasClicked" object:nil];
}
并且在 viewCotroller.m 中,我在初始化部分添加了观察者:
- (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 中,使用某种方法声明一个协议,
在您的 header 顶部:
@protocol CustomViewDelegate : NSObject
- (void)customViewDidSelectButton;
@end
在界面中。
@interface CustomView : NSObject
---
@property (nonatomic, weak) id <CustomViewDelegate> delegate;
---
@end
实施中:
- (void) buttonWasClicked {
[self.delegate customViewDidSelectButton];
}
在视图控制器中观察
在实现文件中添加 <CustomViewDelegate>
(与放置 TableViewDelegate 等的位置相同)
然后当您创建 CustomView
集时,它会委托给自己。
实现委托方法:
- (void)customViewDidSelectButton {
// button was clicked in customView so do something
}