Objective-C边学边记-4:OOP之 复合、存取方法
if(self = [ super init] { …
若要超类可以完成所需的一次性初始化,需要调用[super init]。init方法返回的值(id型数据,即泛型对象指针)描述了被初始化的对象。
将[super init]的结果赋给self是Objective-C的标准惯例。这么做是为了防止超类在初始化过程中返回的对象不同于原先创建的对象。
- (id) init // 初始化对象 { if (self = [super init]) { // 初始化内容 } return self; }
存取方法
存取方法(accessor method)是用来读取或改变对象特定属性的方法。
setter方法:术语修改方法(mutator)是用来改变对象状态的方法。
getter方法:getter方法为使用对象的代码提供了读取对象属性的途径。
注意:在对其他对象的属性进行操作时,应该始终使用对象所提供的存取方法,永远不要直接改变其他对象属性的数值。例如main()不应通过 car->engine 直接改变engine属性的值,而应使用setter方法进行更改。
命名规范:setter方法根据它所更改的属性的名称来命名,并加上前缀"set",getter方法则仅仅根据其返回的属性的名称来命名(不加get前缀)。
#import <Foundation/Foundation.h> /* * car3: 添加新的汽车引擎V8 和 轮胎WeatherRadial * */ @interface Engine : NSObject @end @implementation Engine - (NSString *) description { return (@"I am a Engine"); } @end @interface Tire : NSObject @end @implementation Tire - (NSString *) description { return(@"I am a Tire"); } @end #pragma mark *** Car *** @interface Car : NSObject { Engine *engine; Tire *tires[4]; } // 添加getter,setter - (Engine *) engine; - (void) setEngine:(Engine *) m_engine; - (Tire *) tireAtIndex: (int) index; //通过索引器访问该属性 - (void) setTire: (Tire *) m_tire : (int) index; - (void) print; @end @implementation Car //- (id) init // 初始化Car //{ // if (self = [super init]) { // engine = [Engine new]; // // tires[0] = [Tire new]; // tires[1] = [Tire new]; // tires[2] = [Tire new]; // tires[3] = [Tire new]; // } // // return self; //} - (Engine *) engine { return engine; } - (void) setEngine:(Engine *)m_engine { engine = m_engine; } - (Tire *) tireAtIndex:(int)index { if (index < 0 || index > 3) { NSLog(@"bad index (%d) in \"tireAtIndex:\"", index); exit(1); } return tires[index]; } - (void) setTire:(Tire *)m_tire :(int)index { if (index < 0 || index >3) { NSLog(@"bad index (%d) in \"setTire:atIndex\"", index); exit(1); } tires[index] = m_tire; } - (void) print { NSLog(@"%@",engine); NSLog(@"%@",tires[0]); NSLog(@"%@",tires[1]); NSLog(@"%@",tires[2]); NSLog(@"%@",tires[3]); } // 如果没有重写description方法,则 %@ 将输出对象的内存地址。 // 如: <Car: 0x10010c480> - (NSString *) description { return @"I am a Car!"; } @end // ******************* // V8 Engine Class @interface V8 : Engine @end @implementation V8 - (NSString *) description { return @"I am a V8 Engine!"; } @end // V8 // ******************* // WeatherRadial Tire @interface WeatherRadial : Tire @end @implementation WeatherRadial - (NSString *) description { return (@"I am a WeatherRadial Tire!!"); } @end int main (int argc, const char * argv[]) { Car *car; car = [Car new]; V8 *engine = [V8 new]; [car setEngine: engine]; int i; for (i = 0; i < 4; i++) { WeatherRadial *tire = [WeatherRadial new]; [car setTire:tire :i]; } [car print]; return 0 ; }
复合还是继承?
继承在对象间建立了“is a”的关系,如果能说X是一个Y,就可以使用继承。
复合建立的则是“has a”的关系,如果能说X有一个Y,就可以使用复合。
本站采用知识共享署名-非商业性使用-相同方式共享 2.5 中国大陆许可协议进行许可。
转载请注明:转载自 Elf Sundae's Blog(http://www.cnblogs.com/elfsundae) (小糊涂闲)
转载请注明:转载自 Elf Sundae's Blog(http://www.cnblogs.com/elfsundae) (小糊涂闲)