In Swift, How to Remove a Uiview from Memory Completely

In Swift, how to remove a UIView from memory completely?

In order to have aView to be deinitialised and removed from memory you need to make it unreferenced by anything that keeps a strong reference to it. That means it should not be referenced by any part of your code, and by the UIKit view stack.

In your case it might look like this:

aView?.removeFromSuperview() // This will remove the view from view-stack
// (and remove a strong reference it keeps)

aView = nil // This will remove the reference you keep

On a side note, if you are removing the view, then you probably should not use var aView: UIView! but instead var aView: UIView?.

Removing UIView From Subview clears the memory?


waveView?.onTimeSelected = {newPosition in
DispatchQueue.main.async {
self.waveViewTimeSelected(newPosition: newPosition)
}
}
waveView?.onMarkerSelected = {
DispatchQueue.main.async {
self.waveViewMarkerSelected()
}
}

shouldn't a weak self be used? something like

waveView?.onTimeSelected = {[weak self] _, newPosition in
DispatchQueue.main.async {
self?.waveViewTimeSelected(newPosition: newPosition)
}
}
waveView?.onMarkerSelected = {
DispatchQueue.main.async { [weak self] _ in
self.waveViewMarkerSelected()
}
}

if I am not wrong not using a weak self create a retain cycle, your view won't be deallocated while "self" still exists.

Does UIView's removeFromSuperView method remove the UIView from memory

Yes. Once removeFromSuperView method is called, that view is also released from memory.

If you want to confirm with Apple's documentation, here is the link.

Swift remove reference to UIView

You can weak reference to that UIView. Then the UIView will be nil with ARC after you removed it by using removeFromSuperview.

how to remove subview from view and also release memory

Your code looks good only. If you are using arc then no need to worry about releasing of memory. Because in arc you cannot directly control when an object is released, ARC parses your code and inserts release statements as soon as objects can be released. This frees up the memory for new allocations straight away. Refer this



Related Topics



Leave a reply



Submit