Search code examples
iosswiftmemory-managementdeallocdeinit

Can we use deinitialized variables in code, or are they pretty much useless because they are deallocated right after?


Im a little confused on the topic of deallocation when comparing it to deinitaizlization. Doesn't deallocation happen the moment after a variable is deinitialized.....My main point here is, Could we use/manipulate deinitialized variables somehow? or they are pretty much useless because deallocation takes place right after...?


Solution

  • In Swift the deinit method is called as part of the deallocation process. Precisely when the memory allocated to an object is released you cannot know, but you can't access the object after it has been deinitalised.

    Aside from it not making any sense to do so, it isn't possible to manipulate the object after deinit since the deallocation process is initiated by the removal of the last strong reference to the object. as there are no references how could you manipulate the object anyway. (I suppose you could use an unowned/unsafe reference to attempt to access the object but this would result in your app crashing)