iOS - self & super 理解的关键点

来源:互联网 发布:java开发环境下载 编辑:程序博客网 时间:2024/06/01 10:53

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
原创粉丝点击