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
- iOS - self & super 理解的关键点
- iOS 中self和super如何理解?
- self,super 实例方法的一点理解
- if(self = (super init))的理解
- 对 self = [super init] 的理解
- self = [super init]; if (self) { 与 if (self == [super init]) { 的理解
- IOS Super的理解
- ios开发self和super的区别
- 理解RMI的关键点
- self与super 怎么理解?
- self = [super init]理解
- OC中的self、super理解
- iOS 之self和super
- IOS self = [super init];
- iOS学习——self和super关键字的解析
- super和self之间的区别,还有super可以使用点语法么
- super和self之间的区别,还有super可以使用点语法么
- IOS关于SELF点的一些事情
- 城里城外
- DownloadManager
- wpa_supplicant daemon server & GUI test message
- 练车经验
- 破解WPA/WPA2 for Non-Dictionary Passphrase
- iOS - self & super 理解的关键点
- Cocos2d-x Lua中实例:特效演示
- 黑马程序员——java语言基础部分——String、StringBuffer StringBuild学习笔记一
- js中将字符串转换成json的三种方式
- Log4j配置实例(log4j.xml)
- gloox消息发送与接受剖析
- hadoop2.6.0部署好环境后写的一个简单的test
- 最接近点问题
- 运行junit测试报javax/servlet/ServletContext : Unsupported major.minor version 51.0错误