Objective-C:知道是否释放了内存位置 [英] Objective-c: know if memory location was deallocated
问题描述
我已经为iOS项目实现了下载程序.它接受请求,下载完成后,由委托人响应目标.它是异步的,目标(显然)是一个弱引用,因此当下载完成时,如果不再分配目标,则将得到bad_acces. 我解决了添加一个方法(当使用该对象的对象被释放时调用)的方法,该方法在所有请求中搜索目标并将其设置为nil. 这与我想要的行为相去甚远(完全独立于其他对象:如果不再请求下载,它将被缓存:它没有停止下载的方法,只有优先级队列) 有一种安全的方法可以知道指针是否仍然指向有效的内存地址?
I have implemented a downloader for iOS projects. It accepts requests and, when download has finished, responds to a target by a delegate. It is asynchronous and the target is (obviously) a weak reference so when the download is complete, if the target is no more allocated, I've got a bad_acces. I've resolved adding a method (called when an object that use it is deallocated) that search for the target in all requests and sets it to nil. This is so far from the behavior I wanted (completly independent from other objects: if a download is no more requested it will be cached: it has no method to stop the download but only a priority queue) There is a safe way to know if a pointer still point to a valid memory address?
推荐答案
在回答您的问题时,没有一种很好的方法知道指针仍然有效(除了僵尸以外,它不是生产工具,环境解决方案,只是一个测试环境工具).但是,您不必担心我怎么知道这是否是一个悬空指针",而应该只允许悬空指针从一开始就不会出现.
In answer to your question, there isn't a good way of knowing that a pointer is still valid (other than zombies, which isn't a production-environment solution, just a test-environment tool). But rather that worrying about "how do I know if this is a dangling pointer or not", you should just not allow dangling pointers from occurring in the first place.
创建下载程序时,您大概指定了一个委托.当作为委托的对象将消失时(例如,在其dealloc
中),它应该告诉下载程序将其委托属性设置为nil
,从而消除了悬空的指针.
When your downloader was created, you presumably specified a delegate. When the object that is the delegate is going to disappear (e.g. in its dealloc
), it should tell the downloader to set its delegate property to nil
, thus eliminating the dangling pointer.
这篇关于Objective-C:知道是否释放了内存位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!