gpt4 book ai didi

ios - 自定义类的 Objective-C 多重嵌套 initWith

转载 作者:可可西里 更新时间:2023-11-01 04:11:31 25 4
gpt4 key购买 nike

我是 Objective-C 的新手,我有一个问题。

我创建了一个自定义类并尝试为初始化创建重载:

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

-(id) initWithID:(NSInteger)id {
if(self = [self init]) {
[self setID:id];
}
return self;
}

-(id) initWithID:(NSInteger)id CarYear:(NSString *)year {
if(self = [self initWithID:id]) {
[self setCarYear:year];
}
return self;
}

假设我在某一时刻调用了 -(id) initWithIDCarYear 方法。

我想知道上面的代码在结构上是否正确。

  • 在这段代码中,self 被设置了 3 次。有没有更好的解决方案?
  • 这段代码中是否存在内存泄漏? (使用 ARC)
  • 我是否必须始终检查 if(self = ...) 还是它是一个冗余代码?

谢谢

@编辑下面的代码更好吗?

-(id) initWithID:(NSInteger)id CarYear:(NSString *)year {
if (self = [super init]) {
[self setIsCurrentCar:NO];
[self setID:id];
[self setCarYear:year];
}
return self;
}

最佳答案

虽然您的代码没问题,但我会以相反的顺序构建初始化调用,其中最详细的是指定的初始化器,而更通用的是一些默认值:

-(id) initWithID:(NSInteger)id 
CarYear:(NSString *)year
{
if(self = [super init]) {
_year = year;
_id = id;
}
return self;
}

-(id)initWithID:(NSInteger)id
{
return [self initWithID:id CarYear:@"unset"];
}

-(id)init
{
return [self initWithID:0];
}

如果调用更通用的初始化程序之一会生成非法状态,您可以改为抛出错误以禁止使用它。

假设,汽车需要有 ID,但不需要年份。使用initWithID是可以的,但是使用init会导致状态不一致,所以我们想强制不要使用它:

-(id)init 
{
[NSException raise:NSInternalInconsistencyException
format:@"You must use -initWithID: or -initWithID:CarYear:", NSStringFromSelector(_cmd)];
return nil;
}

  • In this code, self is set for 3 times. Is there a better solution?

见上文

  • Do I have memory leak in this code? (using ARC)

没有,一切都很好

  • Do I have to check for if(self = ...) always or it is a redundant code?

正如我向您展示的:您可以在一个链中调用不同的 init 方法。只有该链中的最后一个需要执行该操作。


-(id) initWithID:(NSInteger)id CarYear:(NSString *)year {
if (self = [super init]) {
[self setIsCurrentCar:NO];
[self setID:id];
[self setCarYear:year];
}
return self;
}

你不应该在初始化方法中对自己使用 setter,see Apple's docs .

关于ios - 自定义类的 Objective-C 多重嵌套 initWith,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13995718/

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