views:

38

answers:

1

My code is really simple. One TableViewController with an instance variable "dataArray", the table is filled as the view appears.

Problem: when I click on one of the entries (didSelectRowAtIndexPath), my app crashes. After debuging this example I have figured out, that "dataArray" has no objects at this time, but why? How can I display the row that was clicked?

Header file:

#import <UIKit/UIKit.h>

@interface DownloadTableViewController : UITableViewController {
 NSMutableArray *dataArray;
}

@property (nonatomic, retain) NSMutableArray *dataArray;

@end

.m File:

#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
+5  A: 

This line:

dataArray = [NSMutableArray arrayWithObjects:@"Mac OS X", @"Windows XP", @"Ubuntu 10.04", @"iOS 4.2", nil]; 

should be this:

dataArray = [[NSMutableArray alloc] initWithObjects:@"Mac OS X", @"Windows XP", @"Ubuntu 10.04", @"iOS 4.2", nil]; 

or

self.dataArray = [NSMutableArray arrayWithObjects:@"Mac OS X", @"Windows XP", @"Ubuntu 10.04", @"iOS 4.2", nil];

or

[self setDataArray:[NSMutableArray arrayWithObjects:@"Mac OS X", @"Windows XP", @"Ubuntu 10.04", @"iOS 4.2", nil]];

The reason your app crashes is because dataArray is autoreleased, and so is deallocated before you ever use it.

Wevah
Thank you so much! :)
adamseve