mvc顧名思義model,view,controller
controller包含model,view
-------------controller.h--------------
#import <Foundation/Foundation.h>
#import "cocos2d.h"
#import "mvcModel.h"
#import "mvcView.h"
@interface mvcController : NSObject <CCTouchOneByOneDelegate>
{
mvcModel *mymodel;
mvcView *myview;
}
@property (nonatomic, retain) mvcModel *mymodel;
@property (nonatomic, retain) mvcView *myview;
@end
-------------controller.m--------------
#import "mvcController.h"
@implementation mvcController
@synthesize mymodel,myview;
-(id) init {
if (self=[super init])
{
// 一個數據模型對應一個view,如果多個模型就對應多個view,在controller中增加array保存對它們的管理
self.mymodel = [[[mvcModel alloc]init] autorelease];
self.myview = [[[mvcView alloc]init] autorelease];
// 實現CCTouchOneByOneDelegate接口,使得controller獲取touch事件
[[[CCDirector sharedDirector] touchDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
}
return self;
}
// touch事件方法
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
static int x = 1;
// 修改model中的title屬性,view會自動修改
self.mymodel.title = [NSString stringWithFormat:@"第%d下",x];
self.mymodel.mypos = CGPointMake(100+x, 100);
// 調用方法使model的改變通過view顯示
[self.mymodel didChange:self.myview];
x++;
return YES;
}
- (void)dealloc
{
[[[CCDirector sharedDirector] touchDispatcher] removeDelegate:self];
[mymodel release];
[myview release];
[super dealloc];
}
@end
-------------model.h--------------
#import <Foundation/Foundation.h>
// 接口部分
@class mvcModel;
@protocol ModelDelegate <NSObject>
@required
-(void)modelDidChange:(mvcModel *)model;
@end
@interface mvcModel : NSObject
{
NSMutableSet *delegates;
NSString *title;
CGPoint mypos;
}
@property (nonatomic, retain) NSString *title;
@property (nonatomic) CGPoint mypos;
-(void)didChange:(id<ModelDelegate>)delegate;
@end
-------------model.m--------------
#import "mvcModel.h"
@implementation mvcModel
@synthesize title,mypos;
-(id)init {
if (self=[super init]) {
delegates = [NSMutableSet new];
}
return self;
}
// 調用接口中的方法,既調用了實現接口的view中方法
-(void)didChange:(id<ModelDelegate>)delegate
{
[delegate modelDidChange:self];
}
- (void)dealloc
{
[title release];
[super dealloc];
}
@end
--------------view.h---------------
#import "cocos2d.h"
#import "mvcModel.h"
// 實現model接口
@interface mvcView : CCLabelTTF<ModelDelegate>
@end
--------------view.m--------------
#import "mvcView.h"
#import "mvcController.h"
@implementation mvcView
-(id) init {
if (self=[super initWithString:@"mvc模式" fontName:@"Marker Felt" fontSize:32])
{
self.anchorPoint = ccp(0.5, 0.5);
self.position = ccp(320/2, 480/2);
}
return self;
}
// model改變調用接口方法更改view顯示
-(void)modelDidChange:(mvcModel *)model
{
self.string = model.title;
self.position = model.mypos;
}
@end
總結controller完成了和用戶的交互部分,
controller修改了自己包含的model,
model改變後通過協議更改了controller中的view展示給用戶