UITextField.Text property = EXC_BAD_ACCESS

Ok … so while I have a couple iPhone/iPad apps under by belt I am still “learning” a view things.  Memory management on these devices seems to be primarily an “art” vs. pure science.  Here is an example of that.

My typical rule is if I created the object then I release it … not 100% fool-proof but it at least gets me thinking in the correct direction.  In this case it messed me up!

I have several UITextField views on my view and I was creating a method to load the values into these fields from the database.  Then the strange behavior stared.  If I had a “space” in the value it would crash upon loading the data into the field with an EXC_BAD_ACCESS in obj_msgsend().  If it did NOT have a space in the value it would only crash when I tried to reference the field’s text value when trying to save subsequently updated data.

The short story was that I was creating an NSString, loading it with data, assigning it to UITextField.text and then releasing the NSString.  This was the issue … this was also causing the text property to get released and was eventually causing the EXC_BAD_ACCESS.

UPDATE:  After going back and re-reviewing the code what I was doing was using a convenience method on a NSString instead of an alloc which meant it was put into the autorelease pool and thus it was getting release two times in that method … once when I release it and once when the pool was drained (and, of course, again when the UITextField was released).

Awesome.

Advertisements