答案取决于display.text 是什么。如果是不可变字符串:
• 一个读/写对象属性(例如property (readwrite, assign) NSString *text;);或
• 结构的字段(例如struct { NSString *text; ... })
那么你需要做的核心是通过附加newText来创建一个new字符串:
display.text = [display.text stringByAppendingString:newText];
如果您正在使用自动垃圾收集,那么您就完成了。
如果不是,您需要知道display.text 的所有权。假设display.text 拥有它的值(通常情况下)并且属性或结构字段定义如上,那么代码变为:
NSString *oldText = display.text;
display.text = [[oldText stringByAppendingString:newText] retain]; // create new string and retain
[oldText release]; // release previous value
现在在属性情况下,您可以定义属性本身来执行retain/release,方法是将其定义为:
property (readwrite, retain) NSString *text;
然后追加回到:
display.text = [display.text stringByAppendingString:newText];
现在display.text 可能是一个可变 字符串,如果您打算向它附加很多值,这是一个好主意,那就是:
• 读/写对象属性(例如property (readwrite, assign) NSMutableString *text;);或
• 结构的字段(例如struct { NSMutableString *text; ... })
然后你添加一个新的字符串使用:
[display.text appendString:newText];
就是这样。 (在属性情况下,是否指定 retain 无关紧要 - 代码相同。)
自动垃圾回收、对象所有权以及不可变和可变类型之间的区别是理解 Objective-C 语义的核心 - 理解所有这些情况,你就会一路走好!