iOS - self & super 理解的关键点

1. method 搜寻路径

(在运行时,调用的到底是哪个 setOrigin::)

- reposition
{
 ...
 [self setOrigin:someX :someY];
 ...
}
或者:

- reposition
{
 ...
 [super setOrigin:someX :someY];
 ...
}

规则:

系统在解析 self 的时候,跟继承链没关系,哪个对象收到消息,self就指的是哪个对象,也就是运行时确定 self 到底指的是谁;
系统在解析 super 的时候,似乎是编译时就定死了,就看 super 是在哪个类方法里出现的,然后调用其父类(或者沿着继承链向上追溯)的该方法,跟消息的接收者没关系。


2. self 在不同语境下有不同含义:

Inside an instance method, self refers to the instance; but inside a class method, self refers to the class object. 

This is an example of what not to do:

+ (Rectangle *)rectangleOfColor:(NSColor *) color
{
 self = [[Rectangle alloc] init]; // BAD
 [self setColor:color];
 return [self autorelease];
}

To avoid confusion, it’s usually better to use a variable other than self to refer to an instance inside a class

method:

+ (id)rectangleOfColor:(NSColor *)color
{
 id newInstance = [[Rectangle alloc] init]; // GOOD
 [newInstance setColor:color];
 return [newInstance autorelease];
}

In fact, rather than sending the alloc message to the class in a class method, it’s often better to send alloc
to self. This way, if the class is subclassed, and the rectangleOfColor: message is received by a subclass,
the instance returned is the same type as the subclass(for example, the array method of NSArray is inherited

by NSMutableArray).

+ (id)rectangleOfColor:(NSColor *)color
{
 id newInstance = [[self alloc] init]; // EXCELLENT
 [newInstance setColor:color];
 return [newInstance autorelease];
}

这些是从apple官方文档里摘录的,英文很简单,再配合例子,就没必要翻译了。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值