实现 Implementation 实现的定义与接口很相似,以 @implementation 指令开 @end 始,以 指令结束: @implementation ClassName : ItsSuperclass { instance variable declarations } method definitions @end 实现 实现必须包含自己的接口文件,比如 Rectangle.m Rectangle.h 文件中必须包含 由于接口中已经进行了声明,实现的定义中有两部分 可以省略: 父类名 实例变量声明 实现 如此便简化了实现的定义: #import "ClassName.h" @implementation ClassName method definitions @end 实现 语言函数,使用方法声明中同样的命 名格式,以一对大括号来括起具体的实现代码: + (id)alloc { ... } 方法的定义结束后不要再加上分号结尾 C 方法的定义如同 实现 访问器的基本实现: - (void)setFilled:(BOOL)flag { filled = flag; ... } - (BOOL)isFilled { return filled; } 实现 编译器通过程序结构限制了实例变量的可见度 Scope ( ) 然而同时我们也有相应的机制显式地控制实例变量的 可见度 通过预编译指令,可以将可见度控制在三个层次 This is illustrated in Figure 2-1. Figure 2-1 The scope of instance variables @private @protected A directive applies to all the instance variables listed after it, up to the next directive or th the following example, the age and evaluation instance variables are private, name , jo protected, and boss is public. The class that declares the instance variable 实现 @private 私有:只有类定义内部可访问 @private int age; id job; @public A class that inherits the instance variable Unrelated code @interface Worker : NSObject { char *name; char *evaluation; @protected @protected 保护:只有类本身和子 类 t wage; @public 公有:程序的任何位置都可访问 floa 的定义里可访问 Class Implementation 实现 @interface Worker : NSObject { char *name; @private int age; char *evaluation; @protected id job; float wage; @public id boss; } 没有指定的实例变量默认的可见度是 protected 实现 private 的必要性: 父类的实例变量不一定要与子类的定义绑死 子类对父类的实例变量进行操作时可能会导致不安 全因素 实现 访问器是专为 protected private 和 变量使用的 public 变量可不通过访问器直接访问,前提是对象已经 被指定为静态类型: Worker *ceo = [[Worker alloc] init]; ceo->boss = nil; public 变量的存在违背了面向对象程序设计的初衷之一 public 封装,因此除非迫不得已,不要使用 变量 oc中有两个关键字可以在方法的实现中代表执行方 法的对象: self :执行方法的对象本身 super :调用对象的父类中的实现来执行方法 self 除了可以用作向自身请求方法以外,还可以作为一 个代表对象本身的隐藏变量来使用 super 只能出现在消息表达式中,代表了对被复写的方 法的原始实现的请求方式 传递消息 superclass – negotiate - makeLastingPeace { superclass – negotiate – makeLastingPeace [super negotiate]; ... superclass – negotiate } 2009年7月31日星期五 28 转载于:https://blog.51cto.com/mkhgg/558210