零基础Objective-C 第三章————–面向对象编程的基础知识(2)
在面向对象编程中使用间接
间接是OOP的核心。OOP真正的革命性在于它使用间接来调用代码。不是直接调用某个函数,而是间接调用。
1. 过程式编程
a.绘制几何体的形状
#import <Foundation/Foundation.h>
typedef enum{
kCircle,
kRectangle,
kEgg
} ShapeType;
typedef enum{
kRedColor,
kGreenColor,
kBlueColor
} ShapeColor;
typedef struct{
int x, y, width, height;
} ShapeRect;
typedef struct{
ShapeType type;
ShapeColor fillColor;
ShapeRect bounds;
} Shape;
NSString *colorName(ShapeColor colorName){
switch (colorName) {
case kRedColor:
return @"red";
break;
case kGreenColor:
return @"green";
break;
case kBlueColor:
return @"blue";
break;
default:
return @"no clue";
break;
}
}
void drawCircle(ShapeRect bounds, ShapeColor fillColor){
NSLog(@"drawing a circle at (%d %d %d %d) in %@",
bounds.x, bounds.y, bounds.width, bounds.height,
colorName(fillColor));
}
void drawShapes(Shape shapes[], int count){
for(int i = 0; i < count; i++){
switch (shapes[i].type) {
case kCircle:
drawCircle(shapes[i].bounds,
shapes[i].fillColor);
break;
case kRectangle:
drawCircle(shapes[i].bounds,
shapes[i].fillColor);
break;
case kEgg:
drawCircle(shapes[i].bounds,
shapes[i].fillColor);
break;
default:
break;
}
}
}
输出
2017-06-19 20:18:25.372236+0800 Project_Test1[811:279761] drawing a circle at (0 0 10 30) in red
2017-06-19 20:18:25.372418+0800 Project_Test1[811:279761] drawing a circle at (30 40 50 60) in green
2017-06-19 20:18:25.372433+0800 Project_Test1[811:279761] drawing a circle at (15 18 37 29) in blue
Program ended with exit code: 0
2.实现面向对象编程
过程式编程建立在函数之上,数据为函数服务,而面向对象编程则以程序的数据为中心,函数为数据服务。在OOP中,不再重点关注程序中的函数,而是专注于数据。
3.有关术语
类(class)是一种表示对象类型的结构体。
对象(object)是一种包含值和指向其类的隐藏指针的结构体。
实例 (instance)是“对象”的另一种称呼。
消息(message)是对象可以执行的操作,用于通知对象去做什么。
方法(method)是为了响应消息而运行的代码。
方法调度 (method dispatcher)是Objective-C使用的一种机制,用于推测执行什么方法以相应都个特定的消息。
接口 (interface)是类为对象提供的特性描述。
实现 (implementation)是使接口能正常工作的代码。
Objective-C 语言中的OOP
- @interface部分
@interface Shape : NSObject
{
ShapeColor fillColor;
ShapeRect bounds;
}
- (void) setFillColor:(ShapeColor)fillColor;
- (void) setBounds:(ShapeRect)bounds;
- (void) draw;
@end // Shape
在Objective-C中只要看到@符号,就可以把它看成是C语言的扩展。
{
ShapeColor fillColor;
ShapeRect bounds;
}
花括号内,指定了实例变量。
- (void) setFillColor:(ShapeColor)fillColor;
- (void) setBounds:(ShapeRect)bounds;
- (void) draw;
方法声明, 列出了每个方法的名称,方法返回值的类型和某些参数。
@end // Shape
告诉编译器,我们已经完成了Circle类的声明。
2.@implementation部分
通常,接口被称为API (application programming interface)。而真正能够运行的代码位于@implementation部分中。
@implementation Shape
- (void)setFillColor:(ShapeColor)c
{
fillColor = c;
}//setFillColor
- (void)setBounds:(ShapeRect)b
{
bounds = b;
}// setBounds
- (void) draw
{
}
@end
也许我们已经注意到了,我们把参数重新命名为简单的字符c了,@interface和@implementation间的参数名不同是允许的。在这里,我们继续使用参数名fillColor,就会覆盖fillColor实例变量,并且编译器会生成警告信息。
3.实例化对象
为了创建一个新的对象,我们需要向相应的类发送new消息。该类接受并处理完new消息后,我们就会得到一个可以使用的新对象实例。
Shapes *shapes = [Shapes new];