【发布时间】:2012-12-09 08:42:50
【问题描述】:
我是 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;
}
【问题讨论】:
-
我担心内存泄漏的原因是我知道 [super init]、[self init] 和 [self initWithID:id] 创建了 3 个不同的实例,这意味着它们占用了 3 个记忆中不同的地方。使用 ARC,它们何时被释放?
-
不,
init不会创建实例。只有alloc可以。
标签: ios objective-c memory-leaks automatic-ref-counting