OGeek|极客世界-中国程序员成长平台

标题: ios - 对象被释放但没有调用 dealloc [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 00:55
标题: ios - 对象被释放但没有调用 dealloc

在我的应用程序的某个时刻,我从其父 View Controller (我们称其为 B)中删除了一个 View Controller (我们称其为 A)。而且即使 A 不再被引用,它的 dealloc 方法也不会被调用。

我用仪器查了一下,A真的被释放了。活体(A类)数量为0。

NSZombie 未启用,我看到它可能会干扰 dealloc 调用。

dealloc 方法被调用的唯一时刻是 View Controller B 被释放的时候。那一刻,堆栈跟踪是这样的:

#0  0x0001ac78 in -[MyViewController dealloc] <-- This is A
#1  0x021061bf in _objc_deallocOnMainThreadHelper ()
#2  0x029f34d0 in _dispatch_client_callout ()
#3  0x029e1726 in _dispatch_main_queue_callback_4CF ()
#4  0x0274443e in __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ ()
#5  0x026855cb in __CFRunLoopRun ()
#6  0x026849d3 in CFRunLoopRunSpecific ()
#7  0x026847eb in CFRunLoopRunInMode ()
#8  0x046095ee in GSEventRunModal ()
#9  0x0460942b in GSEventRun ()
#10 0x00db4f9b in UIApplicationMain ()
#11 0x00028ea2 in main at /../main.m:17

我不确定dealloc是如何触发的

知道这里会发生什么吗?

-- 编辑

我使用类方法创建 View Controller A:

+ (instancetype)viewController
{
    return [[MyViewController alloc] init];
}

奇怪的是,当我用 [[MyViewController alloc] init] 替换对此类方法的调用时,一切都按预期工作。我不知道发生了什么。有什么想法吗?



Best Answer-推荐答案


我终于找到了发生的事情。

未被dealloc的 View Controller 是通过类方法创建的,例如:
+ (instancetype) createMyViewController

这种方法返回自动释放对象。

我唯一的猜测是,在我的情况下,自动释放池已经耗尽得太晚了。在适当的代码周围添加 @autoreleasepool {} block 可以解决所有问题。

关于ios - 对象被释放但没有调用 dealloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25408225/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4