【发布时间】:2011-12-30 17:56:51
【问题描述】:
我最近在我的一个类中重写了一些代码,这给了我一个 NSString 错误。这是我现在拥有的:
我的班级标题:
@interface MyViewController : UITableViewController {
NSString *myString;
}
@property (nonatomic, retain) NSString *myString; // Or copy instead of retain.
@end
并实现了一些方法:
- (void)viewDidLoad {
myString = @"This is";
if (something) {
myString = [NSString stringWithFormat:@"%@ a string.", myString]; // *1
}
[myString retain]; // <-- Why do I have to retain/copy here?
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row == 0) {
/* Some code for creating a UITextView called myTextView */
// ..and then setting the text property:
myTextView.text = myString; // <-- Crashes here if I don't retain/copy in viewDidLoad.
}
}
经过一些调试后,我认为我必须保留/复制 NSString。
如果我想稍后使用它,为什么我必须保留/复制 viewDidLoad 中的 NSString?
另外,我注意到如果我删除标记为 *1 的行,我就不必保留/复制。
【问题讨论】:
标签: ios memory-management nsstring copy retain