在init中调用dealloc? [英] Calling dealloc in init?
问题描述
我正在编写一个框架,并且有一个带有自定义init方法的对象:
I am writing a framework and I have an object with a custom init method:
@implementation OSDatabase
@synthesize database;
// MEM
- (void)dealloc {
sqlite3_close(database);
[super dealloc];
}
// INIT
- (id)initWithDatabasePath:(NSString *)path error:(NSError **)error {
if (self = [super init]) {
if (!sqlite3_open_v2([path UTF8String], &database, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL)) {
error = [NSError errorWithDomain:@"OSDatabaseErrorDomain" code:1 userInfo:nil];
[self dealloc];
return nil;
}
}
return self;
}
@end
如果发生错误,在init
方法内部调用dealloc
是否安全?我对此不确定,内存管理是我一生中最重要的事情之一.
Is it safe to call dealloc
inside of an init
method if an error occoured? I'm not sure about this and memory management is one of the most important things in my life.
谢谢.
推荐答案
如果发生错误,在init方法内部调用dealloc是否安全?
Is it safe to call dealloc inside of an init method if an error occoured?
不.像在其他任何地方一样发送-release
.即使在-init
中,您也不能保证当前保留计数为1.
No. send -release
like you would everywhere else. Even in -init
you can't guarantee that the current retain count is 1.
为什么您从不发送-dealloc
中的[super dealloc]
以外的-dealloc
?原因是您无法保证即使在对象的-init
中,其他对象也可以引用该对象,因为[super init]
可能会选择保留该对象.
Why must you never ever send -dealloc
except [super dealloc]
in -dealloc
? The reason is that you cannot ever guarantee that something else also has a reference to your object, even in your object's -init
because the [super init]
might choose to retain the object.
如果[super init]
返回的对象的保留计数为1,则发送-release
与发送-dealloc
具有相同的效果.如果保留计数大于1,则其他人会认为它拥有该对象,并且对其进行释放将使该对象留下无效的指针,因此-release
仍然是正确的选择.
If the object returned by [super init]
has a retain count of 1, sending -release
will have the same effect as sending -dealloc
. If it has a retain count of more than 1, something else thinks it owns the object and deallocing it would leave it with an invalid pointer, so -release
is still the right thing to do.
另外,这个:
while([self retainCount] != 0){[self release];}
将导致无限循环,并且出于多种原因,这是一个糟糕的主意.对象的保留数永远不会降至0.-release
看起来像这样:
would result in an infinite loop and is a terrible idea for a number of reasons. The retain counts of objects never go down to 0. -release
looks something like this:
- (id)release
{
if (retainCount == 1)
{
[self dealloc];
}
else
{
retainCount--;
}
}
因此循环将保留计数减为1,然后永远持续调用dealloc,直到它导致导致堆错误的堆损坏为止.
so the loop will decrement the retain count to 1 and then continually call dealloc forever or until the heap corruption it has caused leads to a seg fault.
除了永远不会达到零外,保留可能是UINT_MAX
(例如,在字符串或数字文字中),通俗地表示该对象绝不能释放".如果保留计数为UINT_MAX
,则-release
不会减少它.
Apart from never reaching zero, the retain may be UINT_MAX
(for example in string or numeric literals) which colloquially means "this object must never be deallocated". If the retain count is UINT_MAX
, -release
won't decrement it.
这篇关于在init中调用dealloc?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!