1
问:访问实例变量
我想从UITableView的tableView:didSelectRowAtIndexPath:
委托方法访问变量。可以从数据源方法访问该变量,但是当我尝试从诸如此类的委托方法访问该变量时,该应用程序崩溃。
我在.h文件中声明变量,并在applicationDidFinishLaunching
方法中将其初始化为.m文件。我还没有宣布任何访问者/ mutators。
奇怪的是,如果我宣布这样的变量不发生问题:
helloWorld = @"Hello World!";
...但确实,如果我声明变量是这样的:
helloWorld = [NSString stringWithFormat: @"Hello World!"];
关于这里可能发生的任何想法?我错过了什么?
全码:
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
很好,工作。谢谢! – 2009-08-15 03:57:00