5 对象的初始化 [Objective-C基础教程]

//*********************************************************************************
//Tire.h 文件
#import <Cocoa/Cocoa.h>
@interface Tire : NSObject {
float pressure;
float treadDepth;
}
- (id) initWithPressure: (float) pressure;
- (id) initWithTreadDepth: (float) treadDepth;
- (id) initWithPressure: (float) pressure
treadDepth: (float) treadDepth; // 指定的初始化函数
- (void) setPressure: (float) pressure;
- (float) pressure;
- (void) setTreadDepth: (float) treadDepth;
- (float) treadDepth;
@end // Tire

//Tire.m 文件
#import "Tire.h"
@implementation Tire
- (id) init
{
if (self = [self initWithPressure: 34
treadDepth: 20]) {
}

return (self);
} // init
- (id) initWithPressure: (float) p
{
if (self = [self initWithPressure: p
treadDepth: 20.0]) {
}
return (self);
} // initWithPressure
- (id) initWithTreadDepth: (float) td
{
if (self = [self initWithPressure: 34.0
treadDepth: td]) {
}
return (self);
} // initWithTreadDepth

- (id) initWithPressure: (float) p
treadDepth: (float) td
{
if (self = [super init]) {
pressure = p;
treadDepth = td;
}
return (self);
} // initWithPressure:treadDepth:
- (void) setPressure: (float) p
{
pressure = p;

} // setPressure
- (float) pressure
{
return (pressure);
} // pressure
- (void) setTreadDepth: (float) td
{
treadDepth = td;
} // setTreadDepth
- (float) treadDepth
{
return (treadDepth);
} // treadDepth
- (NSString *) description
{
NSString *desc;
desc = [NSString stringWithFormat:
@"Tire: Pressure: %.1f TreadDepth: %.1f",
pressure, treadDepth];

return (desc);
} // description
@end // Tire
//*********************************************************************************
通常的写法: - ( id ) init
{
if ( self = [super init] ) {
. . .
}
return (self) ;
}
注:在自己的初始化方法中,需要调用自己的指定的初始化函数或者超类的指定的初始化函数。一 定
要将超类的初始化函数的值赋给 self 对象,并返回你自己的初始化方法的值。超类可能决定返回一个完 全
不同的对象。

有些类包含多个以 init 开头的方法:
例如 NSString 类中的一些初始化方法:
NSString *emptyString = [[NSString alloc] init] ;
// 返回一个空的字符串
NSString *string = [[NSString alloc] initWithFormat : @"%d or %d",25,624] ;
// 返回一个字符串 , 其值为 25or624
NSString *string = [[NSString alloc] initWithContentOfFile : @"/tmp/words.txt"] ;
// 使用指定路径上的文件中的内容初始化一个字符串
初始化函数的规则:
1 、 若不需要为自己的类创建初始化函数方法,只需要 alloc 方法将内存清 0 的默认行为,不需要担 心
i nit 方法。
2 、 若构造一个初始化函数,则一定要在自己的初始化函数中调用超类的指定的初始化函数。
3 、若初始化函数不止一个,则需要选定一个指定的初始化函数,被选定的方法应该调用超类的指定
的初始化函数。

来源://作者:/更新时间:2012-11-09
相关文章
评论:
验证码:
匿名评论:

最新文章

新热推荐

文章排行