简体   繁体   English

Objective-c super init 是 class 方法还是实例方法?

[英]Objective-c Is super init a class method or instance method?

I am new in objective c. I understand that -init() is an instance method and return an object eg myObj=[myObj init];我是目标 c 的新手。我知道-init()是一个instance method并返回一个 object 例如myObj=[myObj init]; will return an object myObj.将返回 object myObj.

However, if self =[super init];但是,如果self =[super init]; normally super refer to parent class eg NSObject which is a class, not instance .通常super refer to parent class 例如NSObjectclass, not instance

So, Is -init() instance method or class method for super init?那么, Is -init() instance method or class method for super init?

thanks谢谢

init is an instance method. init是一个实例方法。 The fact that you call it on super does not change it.您在super上调用它的事实不会改变它。

Keep in mind that super does not represent the class of your object, but your object seen as an instance of its parent class in the class hierarchy.请记住, super并不代表您的 object 的 class,而是您的 object 被视为 class 层次结构中其父 class 的一个实例。

And you never call myObj=[myObj init];你永远不会调用myObj=[myObj init]; — you call myObj = [[MyObj alloc] init] . — 你调用myObj = [[MyObj alloc] init] Notice the case difference between myObj (a variable) and MyObj (the class of which this variable is an instance).请注意myObj (变量)和MyObj (class,此变量是其实例)之间的大小写差异。

Generally init is used after alloc in this way:一般这样在alloc之后使用init

MyObject* obj = [[MyObject alloc] init];

and alloc create the object instance, so init is an instance method, and when you override it, it's good habit to call always the parent class init .alloc创建 object 实例,所以init是一个实例方法,当你覆盖它时,总是调用父 class init是个好习惯。

Try to read this article .尝试阅读这篇文章

Super is referring to the methods of the parent class in the current object . Super指的是当前object中父类class的方法。 Calling super init will call the method init on the current object ( self ), but will use the implementation of the super class. So no - init is not a static method (this would be visible due to a + before the init method).调用super init将调用当前 object ( self ) 上的方法init ,但将使用 super class 的实现。所以no - init不是 static 方法(由于 init 方法之前的+ ,这将是可见的)。 you can call super whatMethodYouWantFromSuperclass even though it is not static. Static methods are not called on an object ( self ) but on a class ( [NSObject yourStaticMethod] ).您可以调用super whatMethodYouWantFromSuperclass ,即使它不是 static。Static 方法不会在 object( self )上调用,而是在 class( [NSObject yourStaticMethod] )上调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM