我创建了一个 Person 类,在其中实例化了两个对象:
int main(int argc, const char * argv[])
{
@autoreleasepool {
Person * __weak pweak = [Person new];
Person *p = [Person personWithName:@"Strong" lastName:nil dateOfBirth:nil];
}
return 0;
}
The Person
类覆盖它的dealloc
方法,以便它打印名称Person
被解除分配。
一切都按预期进行,weak 变量没有保留Person
实例还活着,我在日志中看到了这一点(“John”是实例的默认名称Person
目的):
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
但是,如果我在弱变量的赋值中使用工厂方法:
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类的这些方法:
- (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];
}