interface负责声明一个类,implementation负责实现它。 实现类保存在.m文件中。用以区分平常的C文件。
一个实现类的例子
实现类是包含在@implemntation和@end之间的:
#import "Point.h"
@implementation Point
// method implementations
+ (id)new
{
// statements ...
}
+ (id)newWithX: (float)x Y: (float)y
{
// statements ...
}
// ...
- (void)setY: (float)newY
{
// statements ...
}
@end
Super and Self
Objective-C提供了两个关键字Super和Self. Self指的是当前的实例,可以用来调用自己这个实例的其他方法。
- (Foo *) foo
{
if (![self fooIsInitialized])
[self initializeFoo];
return foo;
}
Super用来调用这个实例的父类中的方法。
实例初始化
Objective-C的实例初始化比较诡异,一个类的实例通过调用类的alloc方法(从NSObject继承过来的), 但是却被实例的方法来初始化。这和C++还有Java都不一样。它的contructor是特殊的方法,既不属于类又不属于实例。
SomeComplexClass *c = [[SomeComplexClass alloc] init];
即使你不实现init方法,父类的实现会被调用,或者最终NSObject的init方法会调用,如果任何其他父类都没实现init方法。当然这样可能会导致SomeComplexClass中的一些变量的状态是没有被初始化的。所以你应该总是提供init的实现或者注释一下你的类的用法。
通常,一个类会提供一到多个initWith.....方法来进行初始化的同时为变量赋值,同时还会选择性的提供+new方法和便捷构造方法,具体可以参考下面的例子。
+ new
{
Point *point;
// note "self" refers to the "Point" _class_ object!
point = [[self allocWithZone: NSDefaultMallocZone()] init];
return point;
}
+ newWithX: (float)x0 Y: (float)y0
{
Point *point;
point = [[self allocWithZone: NSDefaultMallocZone()] initWithX: x Y: y];
return point;
}
+ point
{
Point *point;
// note "self" refers to the "Point" _class_ object!
point = [self new];
return AUTORELEASE(point);
}
+ pointWithX: (float)x0 Y: (float)y0
{
Point *point;
point = [self newWithX: x Y: y];
return AUTORELEASE(point);
}
- init
{
return [self initWithX: 0.0 Y: 0.0];
}
// this is the "designated" initializer
- initWithX: (float)x0 Y: (float)y0
{
self = [super init];
if (self != nil)
{
x = x0;
y = y0;
}
return self;
}