Question:
I’m trying to access a variable from the UITableView tableView:didSelectRowAtIndexPath: delegate method. The variable can be accessed from the data source methods, but when I try to access it from delegate methods such as this one, the app crashes.
I declare the variable in my .h file, and initialise it in .m file in the applicationDidFinishLaunching method. I haven’t declared any accessors/mutators.
The weird thing is that the problem doesn’t occur if I declare the variable like this:
helloWorld = @"Hello World!";
…but it does if I declare the variable like this:
helloWorld = [NSString stringWithFormat: @"Hello World!"];
Any ideas on what may be going on here? What am I missing?
Full code:
UntitledAppDelegate.h:
#import <UIKit/UIKit.h>
@interface UntitledAppDelegate : NSObject <UIApplicationDelegate, UITableViewDelegate, UITableViewDataSource> {
UIWindow *window;
NSString *helloWorld;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@end
UntitledAppDelegate.m:
#import "UntitledAppDelegate.h"
@implementation UntitledAppDelegate
@synthesize window;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
helloWorld = [NSString stringWithFormat: @"Hello World!"];
NSLog(@"helloWorld: %@", helloWorld); // As expected, logs "Hello World!" to console.
[window makeKeyAndVisible];
}
- (void)dealloc {
[window release];
[super dealloc];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = @"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] autorelease];
}
cell.textLabel.text = @"Row";
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"helloWorld: %@", helloWorld); // App crashes
}
@end
You need to retain your
helloWorldinstance variable. Try this:It worked in the first instance because static strings are ‘infinitely retained’, and so are never deallocated. In the second, your instance variable is being released once the event loop runs. Retaining it will prevent this.