我创建了一个 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;
}
Person
类重写了它的 dealloc
方法,因此它打印了被释放的 Person
的名字。
一切都按预期进行,弱变量不会使 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];
}
最佳答案
当你通过 alloc/init
方法分配一个对象时,ARC 赋予了对象的创建者稍后释放它的责任(所以当你将一个对象存储为 __strong 时,它会一直存在直到有人拥有它,当您将它存储为 __weak 时,它会被释放,因为没有人拥有它。
来自 Apple 文档 ( http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/memorymgmt/Articles/mmRules.html#//apple_ref/doc/uid/20000994-BAJHFBGH )
You own any object you create You create an object using a method whose name begins with “alloc”, “new”, “copy”, or “mutableCopy” (for example, alloc, newObject, or mutableCopy).
在处理工厂方法时,ARC 将返回变量视为自动释放,因此当池被耗尽时它们将被释放。实际上,ARC 将您的工厂方法转换为:
+ (id)personWithName:(NSString *)name lastName:(NSString *)lastName dateOfBirth:(NSDate *)birth
{
return [[[self alloc] initWithName:name lastName:lastName dateOfBirth:birth] autorelease];
}
关于objective-c - 使用工厂方法设置 __weak 变量似乎会使对象保持事件时间过长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14484923/