开发者

Setting UITableViewCell crashes simulator

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)view开发者_开发技巧DidLoad {
    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?


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...];


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.


Yes it's because of some retained memory of the array . U should release the Location array Ivar at the dealloc method.Use this Code

NSArray *array = [[NSArray alloc] initWithObjects:@"1",@"2",@"3",@"4",nil];
self.locationArray = array ;
[array release];

In the Dealloc method

 [locationArray release];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜