使用工厂方法设置__weak变量似乎会使对象存活的时间过长 [英] Using a factory method to set a __weak variable seems to keep the object alive too long
问题描述
我创建了一个Person类,实例化了两个对象:
I've created a Person class, of which I instantiate two objects:
int main(int argc, const char * argv[])
{
@autoreleasepool {
Person * __weak pweak = [Person new];
Person *p = [Person personWithName:@"Strong" lastName:nil dateOfBirth:nil];
}
return 0;
}
Person
类将覆盖其dealloc
方法,以便打印正在被释放的Person
的名称.
The Person
class overrides its dealloc
method, so that it prints the name of the Person
being deallocated.
一切都按预期进行,弱变量不能使Person
实例保持活动状态,我在日志中看到了这一点("John"是Person
对象的默认名称):
Everything goes as expected, the weak variable doesn't keep the Person
instance alive, I see this in the log ("John" is the default name of a Person
object):
2013-01-23 17:36:51.333 Basics[6555:303] John is being deallocated
2013-01-23 17:36:51.335 Basics[6555:303] Strong is being deallocated
但是,如果我在分配给弱变量的过程中使用了工厂方法:
However, if I use the factory method in the assignation to the weak variable:
int main(int argc, const char * argv[])
{
@autoreleasepool {
Person * __weak pweak = [Person personWithName:@"Weak" lastName:nil dateOfBirth:nil];
Person *p = [Person personWithName:@"Strong" lastName:nil dateOfBirth:nil];
}
return 0;
}
这是我看到的记录:
2013-01-23 17:44:16.260 Basics[6719:303] Strong is being deallocated
2013-01-23 17:44:16.262 Basics[6719:303] Weak is being deallocated
我做错什么了吗?
有关Person类的这些方法:
These methods of the Person class may be concerned:
- (id)initWithName:(NSString *)name lastName:(NSString *)lastName dateOfBirth:(NSDate *)birth {
self = [super init];
if (self) {
_name = name;
_lastName = lastName;
_dateOfBirth = birth;
}
return self;
}
+ (id)personWithName:(NSString *)name lastName:(NSString *)lastName dateOfBirth:(NSDate *)birth {
return [[self alloc] initWithName:name lastName:lastName dateOfBirth:birth];
}
推荐答案
通过alloc/init
方法分配对象时,ARC赋予对象创建者负责稍后释放它的责任(因此,当您将对象存储为__strong它会一直存活,直到有人拥有它为止;当您将其存储为__weak时,它会被释放,因为没有人拥有它.)
When you allocate an object via the alloc/init
method ARC gives to the creator of the object the responsability to release it later (so when you store an object as __strong it will stay alive until somebody owns it and when you store it as __weak it gets deallocated because nobody owns it).