现在的位置: 首页 > 综合 > 正文

用例子说明MVC 设计模式(以Objective-C 实现)

2013年01月30日 ⁄ 综合 ⁄ 共 2025字 ⁄ 字号 评论关闭

要实现的功能:

对窗体上一个复选框,标签修改,按钮事件进行演示

Xcode新建一个项目

File  ->  Creat Project  ->  Cocoa Application  ->  MyProject(项目名)

创建一个底层实现类(模型Model)

Xcode 项目中选中Classes 文件夹

File  ->  New File  ->  baseClass(文件名)  ->  选中Also create "baseClass.h"

创建一个中间控制类(中间层Controller)

双击  MainMenu.xib(Resources目录下) 文件来启动 Interface Builder

从Tools  ->  Library 中把Object 拉到 XIB 项目中

选中Object ,从菜单中 Tools  ->  identity Inspector

Class identity 栏中Class 命名:controlClass

Class Outlets 栏中添加两项:isChecked , lableValue

Class Actions 栏中添加一项:executeClick:

创建一个窗口(视图View)

从Tools  ->  Library 中拉一个 Push Button ,一个Lable ,一个 Check Box到 XIB 的 Window 窗口中

中间类跟窗口绑定

control + 选中 XIB 窗口中的 Control Class 移动到 Label,从下拉列表中选中lableValue 

以同样的方式实现Check 跟 isChecked 的绑定

control + 选中windows窗口上的Button 移动到 Control Class上,选中下拉列表中executeClick:

为中间控制类创建文件

在XIB 窗口中选中Control Class  ->  FIle  ->  Write Class  ->Objective->  C(Language)  ->Create'.h' file(选中)  ->  Save  ->  选择
加入的项目  ->Add

为了便于管理,不管默认情况下文件放在了哪里,把他们拖到Classes 文件夹中

定义刚建的底层类

Interface 文件

#import <Foundation/Foundation.h>

@interface baseClass : NSObject {

NSString *showValue;

}

-(NSString *)showValue;

-(void)setshowValue:(NSString *)values;

 

@end

 

Implementation 文件

#import "baseClass.h"

@implementation baseClass

-(NSString *)showValue{

return showValue;

}

 

-(void)setshowValue:(NSString *)values{

[values retain];

[showValue release];

showValue=values;

}

 

-(void)dealloc{

[showValue release];

[super dealloc];

}

@end

 

在中间控制类中创建的类中使用底层类

Interface 文件(仅把父类加上)

#import <Cocoa/Cocoa.h>

 

@interface controlClass : NSObject {

IBOutlet id isChecked;

     IBOutlet id lableValue;

}

- (IBAction)executeClick:(id)sender;

@end

 

Implementation 文件

#import "controlClass.h"

#import "baseClass.h"

@implementation controlClass

- (IBAction)executeClick:(id)sender {

baseClass *bClass = [[baseClass allocinit];

NSString *firstName=@"FirstName";

NSString *secondName=@"SecondName";

if([< /span>isChecked state])

[bClass setshowValue:firstName];

else

[bClass setshowValue:secondName];

[lableValue setStringValue:[bClass showValue]];

[baseClass release];

[firstName release];

[secondName release];

}

@end

执行

command + B 编译 连接

command + R 执行, 生成

点击按钮标签显示:复选框选中为FirstName,不选中为SecondName,即实现了界面通过中间层向底层传递信息(Check Box是否选 中),并由中间层把信息显示在界面上(每次要显示的值)

抱歉!评论已关闭.