I recently rewrote some code in one of my classes, which gave me an error with an NSString. Here is what I have now:
My class header:
@interface MyViewController : UITableViewController {
NSString *myString;
}
@property (nonatomic, retain) NSString *myString; // Or copy instead of retain.
@end
And implemented some methods:
- (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.
}
}
After some debugging I figured I had to retain/copy the NSString.
Why do I have to retain/copy the NSString in viewDidLoad if I want to use it later on?
Also, I noticed that if I remove the line marked *1, I don’t have to retain/copy.
If you use the synthesized setter method to assign the variable, it will automatically retain the
NSStringfor you: