在 Objective-C 中创建构造函数
为什么我们在 Objective C 中创建构造函数时总是这样做?
self = [super init];
if ( self ) {
//Initialization code here
}
Why do we always do this when creating constructors in Objective C?
self = [super init];
if ( self ) {
//Initialization code here
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你可以在 Objective-C 中创建构造函数和析构函数
you can create constructor and destructor in objective-c with
我们重新分配给
self
,因为允许[super init]
返回与调用它的对象不同的对象。我们if (self)
因为[super init]
允许返回nil
。We reassign to
self
because[super init]
is allowed to return a different object than the one it was called on. Weif (self)
because[super init]
is allowed to returnnil
.self
是一个基于某些超类的类(例如 UIViewController、NSObject - 请参阅您的界面文件以确定是哪一个)。超类可能需要某种形式的初始化才能使子类按预期工作。因此,通过首先初始化超类,我们确保设置默认属性等。如果不首先初始化超类,我们可能会遇到一些非常意外的行为,尤其是在 ViewController 等更复杂的对象中。self
is a class based on some superclass (e.g. UIViewController, NSObject - see your interface file to be sure which one). The superclass might need some form of initialization in order for the subclass to work as expected. So by first initializing the superclass we make sure default properties and the like are set. Without initializing the superclass first, we might experience some very unexpected behavior, especially in more complex objects like ViewControllers and the like.阅读这个关于初始化的苹果文档
http://developer.apple.com/库/mac/#documentation/cocoa/Conceptual/ObjectiveC/Chapters/ocAllocInit.html
Read this apple document on initialization
http://developer.apple.com/library/mac/#documentation/cocoa/Conceptual/ObjectiveC/Chapters/ocAllocInit.html