Arcrammer Arcrammer - 2 months ago 9
iOS Question

Why can't I apply the same UIView instance to two separate UITextFields without a memory leak?

I'm really asking why there's a memory leak in the first place.

I have a view controller with two simple

UITextField
objects. I wanted some left indentation so I'd applied the following to them after creating an
IBOutlet
for both:

var textFieldIndentation = UIView(frame: CGRectMake(0, 0, 20, 0))
self.usernameField.leftViewMode = UITextFieldViewMode.Always
self.usernameField.leftView = textFieldIndentation
self.passwordField.leftViewMode = UITextFieldViewMode.Always
self.passwordField.leftView = textFieldIndentation


After around 15 seconds I've noticed my application has taken more than 1.5GB of RAM and it has been using 100% of the processor non-stop.

Why does this happen?

Answer

Don't use the same UIView instance as the leftView for both UITextField objects. Since you have set the leftViewMode to Always, it will repeadetly remove the textFieldIndentation object from one UITextField instance in order to add it to the other UITextField instance.

Simply do

var textFieldIndentationU = UIView(frame: CGRectMake(0, 0, 20, 0))
var textFieldIndentationP = UIView(frame: CGRectMake(0, 0, 20, 0))
self.usernameField.leftViewMode = UITextFieldViewMode.Always
self.usernameField.leftView = textFieldIndentationU
self.passwordField.leftViewMode = UITextFieldViewMode.Always
self.passwordField.leftView = textFieldIndentationP
Comments