是否可以确保在创建对象的同一线程上调用dealloc? [英] Is dealloc guaranteed to be called on the same thread that created the object?

查看:60
本文介绍了是否可以确保在创建对象的同一线程上调用dealloc?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否保证在创建NSObject实例的同一线程上调用dealloc?例如,如果我在主线程上调用[[MyFluffyBunny alloc] init],是否可以保证在主线程上也调用dealloc,或者一旦不再保留MyFluffyBunny可以在任何线程上调用它吗?

Is dealloc guaranteed to be called on the same thread that created a NSObject instance? For example, if I call [[MyFluffyBunny alloc] init] on the main thread, is dealloc guaranteed to also be called on the main thread, or can it be called on any thread once MyFluffyBunny is no longer retained?

我在我的应用程序中看到零星的崩溃,这表明不能保证,但是我一直找不到任何证实它的文档.

I see sporadic crashes in my app that points to that it's not guaranteed, but I've been unable to find any documentation confirming it.

推荐答案

在释放该对象的最后一个强引用的任何线程上,该对象都被释放.也就是说,无论什么线程在最后时间调用-release.实际上是在期间调用-release释放对象.

The object is deallocated on whatever thread releases the last strong reference to it. That is, whatever thread calls -release the final time. It is actually during that -release call that the object is deallocated.

NSObject协议中-release方法的文档说:

The documentation for the -release method in the NSObject protocol says:

减少接收者的参考计数. …当接收者的参考计数达到0时,会向其发送dealloc消息.

《高级内存管理编程指南:实用内存管理》一文将其包含在

The Advanced Memory Management Programming Guide: Practical Memory Management article includes this among the reasons to not use -dealloc to manage scarce resources:

  1. 清理逻辑在错误的线程上执行.

  1. Cleanup logic being executed on the wrong thread.

如果在意外的时间自动释放对象,则该对象将被释放在恰好位于其内的任何线程的自动释放池块中.这对于仅应从一个线程访问的资源来说可能是致命的.

If an object is autoreleased at an unexpected time, it will be deallocated on whatever thread’s autorelease pool block it happens to be in. This can easily be fatal for resources that should only be touched from one thread.

这篇关于是否可以确保在创建对象的同一线程上调用dealloc?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆