实例变量在同一个控制器中是未知的

ada*_*eve 1 iphone objective-c

我的代码非常简单.一个TableViewController带有一个实例变量"dataArray",该表在视图出现时填充.

问题:当我点击其中一个条目(didSelectRowAtIndexPath)时,我的应用程序崩溃了.在调试这个例子后我发现,"dataArray"目前没有对象,但为什么呢?如何显示单击的行?

头文件:

#import <UIKit/UIKit.h>

@interface DownloadTableViewController : UITableViewController {
 NSMutableArray *dataArray;
}

@property (nonatomic, retain) NSMutableArray *dataArray;

@end
Run Code Online (Sandbox Code Playgroud)

.m文件:

#import "DownloadTableViewController.h"

@implementation DownloadTableViewController

@synthesize dataArray;

- (void)viewWillAppear:(BOOL)animated{
 dataArray = [NSMutableArray arrayWithObjects:@"Mac OS X", @"Windows XP", @"Ubuntu 10.04", @"iOS 4.2", nil]; 
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [dataArray count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    cell.textLabel.text = [dataArray objectAtIndex:indexPath.row];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
 NSLog(@"%@", [self.dataArray objectAtIndex:indexPath.row]);
}


- (void)dealloc {
    [super dealloc];
}

@end
Run Code Online (Sandbox Code Playgroud)

Wev*_*vah 5

这一行:

dataArray = [NSMutableArray arrayWithObjects:@"Mac OS X", @"Windows XP", @"Ubuntu 10.04", @"iOS 4.2", nil]; 
Run Code Online (Sandbox Code Playgroud)

应该这样:

dataArray = [[NSMutableArray alloc] initWithObjects:@"Mac OS X", @"Windows XP", @"Ubuntu 10.04", @"iOS 4.2", nil]; 
Run Code Online (Sandbox Code Playgroud)

要么

self.dataArray = [NSMutableArray arrayWithObjects:@"Mac OS X", @"Windows XP", @"Ubuntu 10.04", @"iOS 4.2", nil];
Run Code Online (Sandbox Code Playgroud)

要么

[self setDataArray:[NSMutableArray arrayWithObjects:@"Mac OS X", @"Windows XP", @"Ubuntu 10.04", @"iOS 4.2", nil]];
Run Code Online (Sandbox Code Playgroud)

您的应用程序崩溃的原因是因为dataArray是自动释放的,因此在您使用它之前已取消分配.