一起学Objective-C - 创建实现类(implementation)

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;
}


注意,首先便捷构造方法( new and newWithX:Y:)执行了 [self allocWithZone:],这里的self指向的是类对象。然后,注意其他的便捷构造方法(point and pointWithX:Y:) 在返回对象的时候执行了autorelease。这遵循了上一篇内存管理的规则。第三,这些new.. 方法都调用了init... 方法,没必要维护这样一个一对一的关系,但是通常会让片接构造方法依赖这些实例init方法。第四,注意这里使用了[self allocWithZone: NSDefaultMallocZone()] 而不是 [self alloc] ,这也不是必要的,但是在性能提供了一点点的好处,因为+alloc最终实现是调用在default zone调用+allocWithZone。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值