Is it possible to manually clear out the contents of an object from memory?
In particular, I'm dealing with NSData
. I've tried using data.length = 0
and data.setData(NSData)
.
I know ARC
will come in and clean up after it is out of scope to whom it belongs, but is it possible to manually force this process when I want?
I think you have some misconceptions about ARC I'd like to clear up. The goal of ARC is is to ensure memory leaks don't occur. It's responsible for tracking the object over its lifecycle, and ensuring it's "freed" when no references remain to it.
It's important to note that the memory being "freed" does not necessarily imply "writing over it all with 0s".
It simply means that memory will be designated as unused. The freed memory becomes a candidate for allocation when the system needs to allocate memory to new objects.
There's no guarantee that this reallocation will happen, thus it's very possible for your freed memory to contain your original data, and never be overwritten.
Update: It looks like since 2022, Apple's platforms do zero memory upon deallocation, because it compresses better, which helps under high memory pressure. https://forums.swift.org/t/erase-dealocated-memory/34964/13
Note that this is just a performance optimization, and certainly not a guarantee that you can rely on for security purposes.