views:

94

answers:

2

In my UIView nib file, I've got a UITableView which takes up about half the screen. The correpsponding .h and .m files are:

// helloViewController.h
#import <UIKit/UIKit.h>
@interface helloViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> {
    NSArray *locationArray;
}
@property (nonatomic, retain) NSArray *locationArray;
@end

// helloViewController.m
@synthesize locationArray;
- (void)viewDidLoad {
    locationArray = [NSArray arrayWithObjects:@"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8",  @"9",  @"10",  @"11", nil];
    [super viewDidLoad];
}


- (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] setText: [locationArray objectAtIndex:[indexPath row]]];

    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 8;
}

When I run this it crashes when I try to scroll the table (with no error in the debugger). However, if I replace [[cell textLabel] setText: [locationArray objectAtIndex:[indexPath row]]]; with

[[cell textLabel] setText:@"Boom"];

... it does not crash....

What is causing this problem? The delegate and datasource are connected to the File's Owner in IB, and the File's Owner's class is set to the correct class. Is it an issue that I'm using a table view within a uiview in the nib?

A: 

It's probably because your locationArray was not previously retained and now points to garbage memory. That, or locationArray does not contain an item at the specified index.

rein
+1  A: 

The problem is that you're setting locationArray to an autoreleased object in viewDidLoad. Then you try to access this object again where you want to set the cell, but the array has been deallocated by then.

You should use the retain-property you defined (you're setting the array directly, not using the property) and read some more on memory management. ;)

self.locationArray = [NSArray arrayWith...];
Pascal
Was I not using locationArray as a property? I had @property-ed and @synthesize-d it. I was under the impression that when you do that it is retained...?
cannyboy
You made it an `@property` however when you set it, you just set it to the ivar itself, not the property. You should thus set it like `self.locationArry = …`
jbrennan
got it. thanks. the 'self.' thing has tripped me up before.
cannyboy
Oh, yes, I forgot to mention that. Thanks jbrennan for clarifying, will edit my answer accordingly.
Pascal