2009-08-15 231 views
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 

回答

3

您需要保留您的helloWorld实例变量。试试这个:

helloWorld = [[NSString stringWithFormat: @"Hello World!"] retain]; 

它在第一个实例中工作,因为静态字符串'无限保留',所以永远不会被释放。在第二种情况下,一旦事件循环运行,您的实例变量就会被释放。保留它将防止这种情况发生。

+0

很好,工作。谢谢! – 2009-08-15 03:57:00