我最近在我的一個類中重寫了一些代碼,這給了我一個NSString的錯誤。以下是我現在有:爲什麼我必須保留/複製這個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的行,我不必保留/複製。
謝謝,這解決了它。 – matsr