Dangling pointers in objective c - does nil also release memory?

和自甴很熟 提交于 2019-12-01 04:17:21

Under ARC

For your first example myCar will be set to nil and the newly created Car will get deallocated at some point. This is because myCar is the only thing that has a reference to your newly created Car.

If something else had a strong pointer to the newly created Car then this would simply nil out myCar's reference and the other interested references would determine the lifetime of the Car instance

Under Non-ARC

People still do this?

Your first example would indeed be a memory leak - you have lost the only pointer to your new Car instance without decrementing the +1 reference from the alloc.

You do the first, ARC does the equivalent of the second. There are no dangling references, with or without the nil assignment, since ARC retained the referenced object (retain count 1) and when execution moves beyond the scope of the myCar definition, ARC will guarantee a release of myCar's referenced object, decrementing the reference count and deallocating the object memory if the resulting reference count is 0.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!