你好,我已经阅读了关于MVC的教程,并在这里阅读了相关主题。我认为我理解了MVC的概念,但我不确定如何实现它。
我尝试将其应用于一个简单的程序,一个带有标签和按钮的窗口。按钮增加计数器,标签显示其值。
我尝试了两种不同的方法。
在第一种情况下(示例有效),我将视图和控制器融合在一起。正如我所说,示例有效,但我想让你们告诉我,这是否是MVC的正确实现,或者它是否没有遵循正确的设计。
第二个示例将模型、视图和控制器作为三个分离的类,但该示例无法工作,因为V和C会相互导入,所以我希望你们告诉我我做错了什么。
第一个版本:模型、视图-控制器
//Model.h
#import <Foundation/Foundation.h>
@interface Model : NSObject {
int _counter;
}
-(void)setCounter:(int)valueCounter;
-(int)getCounter;
-(void)increaseCounter;
@end
//Model.m
#import "Model.h"
@implementation Model {}
-(void)setCounter:(int)valueCounter { _counter = valueCounter; }
-(int)getCounter { return _counter; }
-(void)increaseCounter{ _counter ++; }
@end
//ViewController.h
#import <UIKit/UIKit.h>
#import "Model.h"
@interface ViewController : UIViewController {
IBOutlet UIButton *_button;
IBOutlet UILabel *_label;
Model *myModel;
}
-(IBAction)send:(id)sender;
@end
//ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
myModel = [[Model alloc]init];
_label.text = [NSString stringWithFormat:@"%d",[myModel getCounter]];
}
- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; }
- (IBAction)send:(id)sender{
[myModel increaseCounter];
_label.text = [NSString stringWithFormat:@"%d",[myModel getCounter]];
}
@end
这种方式是MVC的正确模式吗?代码可以运行,但在开始更复杂的应用程序之前,我想确保我以正确的方式编写它。这是我编写此应用程序的方式,我的MVC方式。它是好还是坏?如何改变或修复它?
第二个版本:模型、视图、控制器分离
----> 这是模型
//Model.h
#import <Foundation/Foundation.h>
@interface Model : NSObject {
int _count;
}
-(void)setCount:(int)value;
-(int)getCount;
-(void)increaseCount;
@end
//Model.m
#import "Model.h"
@implementation Model
-(void)setCount:(int)value { _count = value; }
-(int)getCount { return _count; }
-(void)increaseCount { _count = _count++; }
@end
----> 这是视图
//View.h
#import <UIKit/UIKit.h>
#import "Controller.h"
@interface ViewController : UIViewController{
IBOutlet UILabel *label;
IBOutlet UIButton *button;
Controller *myController;
}
@end
//View.m
#import "ViewController.h"
#import "Controller.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
myController = [[Controller alloc]init];
}
- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; }
-(IBAction)pressButton:(id)sender{
label.text = [NSString stringWithFormat:@"%d",[myController actionIncrease]];
}
@end
----> 这是控制器(Controller)
//Controller.m
#import <Foundation/Foundation.h>
@class "Model.h"
@class "ViewController.h"
@interface Controller : NSObject {
Model *_mymodel;
UIViewController *_myviewController;
}
-(int)actionIncrease;
@end
//Controller.m
#import "Controller.h"
#import "Model.h"
@implementation Controller
-(id)init{
_mymodel = [[Model alloc]init];
}
-(int)actionIncrease {
[_mymodel increaseCount];
return [_mymodel getCount];
}
@end
这个版本无法工作,因为视图和控制器之间互相引用,编译器会给出警告。