gpt4 book ai didi

ios - 多级继承的 objective-c [self init]层次结构

转载 作者:行者123 更新时间:2023-12-01 17:26:00 28 4
gpt4 key购买 nike

我有一个继承了B类的A类。并且想要实现类似以下的功能。但是由于动态类型转换,init方法会进行递归调用。
有什么办法可以做到这一点?有什么建议吗? (在子类中不更改'init'的名称?

@interface A : NSObject
@property NSData * data;
@end
@implementation A

- (id) init {
self = [super init];
/* want to do some default initialization here
for this class and all of its subclasses. */
// ... ...
return self;
}

/* This [self init] get recursed.
But how can I force this class and all of its subclass to call [self init] above,
not to call the subclass's init method. */

- (id) initWithData:(NSData *)d {
self = [self init];
self.data = d;
return self;
}

@end
@interface B : A

@end
#import "B.h"

@implementation B

- (id) init {
self = [super initWithData:nil];
// some subclass specific init code here ...
return
}
@end

使用B,
- (void) testInit{
B * b = [[B alloc] init];
}

最佳答案

您正在实现中调用[self init],这导致了递归问题。

实施方式:

- (id) init {
self = [super init];
//Basic empty init...
return self;
}

- (id) initWithData:(NSData *)d
{
self = [super init]; //<---- check this line.

if(self)
{
self.data = d;
}
return self;
}

//如果您只想编写一些初始化代码,则以下代码可以工作...
-(void)oneTimeWrittenInitCode:(id)mySelf
{
//your init code which you wish to write one time goes here...
}

- (id) init {
self = [super init];
if(self)
{
[self oneTimeWrittenInitCode:self];
}
return self;
}

- (id) initWithData:(NSData *)d
{
self = [super init];

if(self)
{
[self oneTimeWrittenInitCode:self];
self.data = d;
}
return self;
}

关于ios - 多级继承的 objective-c [self init]层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19635458/

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