2009-08-15 154 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