gpt4 book ai didi

ios - 何时使用 [Super init] iOS

转载 作者:行者123 更新时间:2023-11-28 21:49:01 24 4
gpt4 key购买 nike

[super init] 在 Objective-C 默认方法中有什么用,在什么情况下我们可以在自定义方法中使用它?

最佳答案

简而言之:

一个。每个类都有一个(通常)或多个主要(指定)初始化器。在您进行自己的初始化之前,您必须执行 super 的主要初始化程序之一。例如,在 NSObject 中,-init 是主要的初始化器。如果您有 NSObject 的子类,则必须在执行自己的初始化之前执行 init (NSObject):

@interface MyClass : NSObject

@end

@implementation MyClass
- (id)init // My primary initializer
{
// Before I do my own -init, if have to execute super's -init
self = [super init];

}
@end

如果你的子类有一个新的主初始化器,这成立:

@interface MyClass : NSObject

@end

@implementation MyClass
- (id)initMyClassWith… // My primary initializer, that's different from NSObject's
{
// Before I do my own -initMyClass, if have to execute super's -init
self = [super init];
// As long, as -init is not overridden, self-init would work by acdident,
// but you have to override on a PI change, see below!

}
@end

当你有一个方便的初始化程序时,你init发送给super(更一般的:执行super的PI)。在这种情况下,您将消息发送给自己:

@interface MyClass : NSObject

@end

@implementation MyClass
- (id)initConvenient // My secondary initializer
{
self = [self initMyClass]; // primary

}
@end

因此在 PI 更改时,您必须重写父类的 PI 以使其执行子类的 PI:

    @interface MyClass : NSObject

@end

@implementation MyClass
- (id)init // subclass' secondary
{
self = [self initMyClass]; // Primary

}
@end

关于ios - 何时使用 [Super init] iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29028789/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com