views:

931

answers:

2

Well, I have a UITextField.

Inside it is a property UITextField.text.

Is it ok to do:

// Assume we have UITextField * tf somewhere..
// now set its text..
tf.text = [ [ NSString alloc ] initWithUTF8String:"Init'd with utf8" ] ;

My problem with this is memory. What happens to the old value of the UITextField's text property.

Don't you have to do:

// maintain reference to old NSString
NSString * oldTfText = tf.text ;

// set the value to the new value you want
tf.text = [ [ NSString alloc ] initWithUTF8String:"Init'd with utf8" ] ;

// release the old NSString now..
[ oldTfText release ] ;

I'm still thinking of memory mgmt as I do in normal C. This might be the flaw here.

+1  A: 

UITextField will be responsible for releasing any old value it has. Your concern is only with your code and you're correct that this alloc'ed NSString must be released.

You can also use autorelease to avoid the extra declaration.

tf.text = [ [ [ NSString alloc ] initWithUTF8String:"Init'd with utf8" ] autorelease];
nall
A: 

tf.text is a setter. Looking at the header files, the property is defined:

@property(nonatomic,copy) NSString *text;

Thus, I would think you should set it this way, and let the system take care of its own copy:

mytext = [ [ NSString alloc ] initWithUTF8String:"Init'd with utf8" ] ;
tf.text = mytext;
[mytext release];
mahboudz