R – class variable accessible at end of one function, and crashes on access at beginning of next

iphonensstringuitableview

(programming in iPhone objective-C)

I have a class level NSString* that I create, add property(nonatomic,retain) and synthesize code for and I can modify the string endlessly with stringByAppendingString functions and display the string using NSLog just fine. All of this is done in a subclass, overridden viewDidLoad function. When I try to access the same variable from the cellForRowAtIndexPath function when determining what to display in the cell of a tableView, the program crashes. Anyone have any clues?

Related Code:

@interface InfoViewController : UITableViewController {
    NSString *shipAddr;
}
@property (nonatomic,retain) NSString *shipAddr;

@synthesize shipAddr;

VIEWDIDLOAD:

shipAddr = [[[NSString alloc] initWithString:@""] retain];

**CRASHES HERE:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(shipAddr);

**

Best Answer

You're actually double-retaining the original string, which leaks it, but that's not the cause of your crash.

You're crashing because stringByAppendingString: returns an autoreleased string. So it doesn't matter how many times you retain the original; every time you call stringByAppendingString: (or any of the other stringByWhatever methods) you get a new string that has a limited lifetime.

For your code, I would suggest simply always assigning to self.shipAddr, and just assigning @"" to the string to begin with. The self.shipAddr version will handle memory management for you automatically.

Related Topic