2009-11-02 63 views
0

嗯,我有一個UITextField。管理UITextField.text屬性

它內部是一個屬性UITextField.text。

它是確定的事情:

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

我這個問題是內存。 會將UITextField的文本屬性的舊值發生什麼情況。

不要你必須做的:

// 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 ] ; 

我還在想着內存MGMT的像我這樣在正常C.這可能是這裏的缺陷。

回答

2

UITextField將負責釋放它具有的任何舊值。你只關心你的代碼,你必須釋放這個alloc的NSString是正確的。

您也可以使用autorelease來避免額外的聲明。

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

tf.text是一個setter。縱觀頭文件,屬性定義:

@property(nonatomic,copy) NSString *text; 

因此,我認爲你應該設置這種方式,並讓系統利用其自己的副本護理:

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