[英]Getting “EXC_BAD_ACCESS” when accessing instance variable from within UITableView delegate method
[英]Accessing instance variables from UITableView delegate methods
題:
我正在嘗試從UITableView tableView:didSelectRowAtIndexPath:
委托方法訪問變量。 可以從數據源方法訪問變量,但是當我嘗試從諸如此類的委托方法訪問變量時,應用程序崩潰。
我在.h文件中聲明了該變量,然后在applicationDidFinishLaunching
方法的.m文件中對其進行了初始化。 我尚未聲明任何訪問器/更改器。
奇怪的是,如果我這樣聲明變量,就不會出現問題:
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
您需要保留helloWorld
實例變量。 嘗試這個:
helloWorld = [[NSString stringWithFormat: @"Hello World!"] retain];
它之所以起作用,是因為靜態字符串是“無限保留”的,因此永遠不會被釋放。 第二,事件循環運行后,實例變量將被釋放。 保留它可以防止這種情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.