objective-c - 使用工厂方法设置 __weak 变量似乎会使对象保持事件时间过长

标签 objective-c memory-management automatic-ref-counting

我创建了一个 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/

相关文章:

objective-c - 将项目添加到 sqlite3 数据库不起作用

objective-c - ASIHttp 同步请求在返回后运行委托(delegate)方法

c++ - 指针还是数组?

c++ - dbgheap.c 抛出访问冲突异常

ios - 为什么会有弱者和无主?为什么我们不能总是使用 weak?

javascript - 识别圆弧上的事件

ios - Tealium 框架 "dyld: Library not loaded:"使用 cocoapods 时出错

objective-c - 更改 MAC 地址 Cocoa - Objective-C

ios - 对象似乎被释放,但内存占用不断增加

ios - EXC_BAD_ACCES 绘图阴影