加载NSMutableArray进入UITableView在Scroll上崩溃

时间:2013-10-15 16:56:27

标签: iphone ios objective-c uitableview

我正在尝试将我的NSMutableArray加载到UITableView中,但滚动后它会崩溃。数据加载到UITableView中,但就像我说我无法滚动。

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize myArray = _myArray;

#pragma mark TableViewStuff

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _myArray.count;
}


//—-insert individual row into the table view—-
- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    //—-try to get a reusable cell—-
    UITableViewCell *cell =
    [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    //—-create new cell if no reusable cell is available—-
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                       reuseIdentifier:CellIdentifier]
                autorelease];
    }

    //—-set the text to display for the cell—-
    NSString *cellValue = [_myArray objectAtIndex:indexPath.row];
    cell.textLabel.text = cellValue;

    return cell;
}
#pragma mark LifeCycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    // Load the file into a string
    NSString* filePath = [[NSBundle mainBundle] pathForResource:@"listOfColleges" ofType:@"txt"];
    NSString* myString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    //Fill the array with subsets of the string
    _myArray = [NSMutableArray arrayWithArray:[myString componentsSeparatedByString:@"\n"]];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

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

@end

MyArray被保留并且它是非原子的,所以我应该好好去。在UITableView可以使用之前,也许有些东西正在消亡?

我得到的错误如下:

EXC_BAD_ACCESS @此行 - NSString *cellValue = [_myArray objectAtIndex:indexPath.row];

1 个答案:

答案 0 :(得分:5)

问题在于:

_myArray = [NSMutableArray arrayWithArray:[myString componentsSeparatedByString:@"\n"]];

您没有访问您的二传手,因此保留不会发生。你想要:

self._myArray = [NSMutableArray arrayWithArray:[myString componentsSeparatedByString:@"\n"]];

[_myArray release];
_myArray = [[NSMutableArray arrayWithArray:[myString componentsSeparatedByString:@"\n"]] retain];

[_myArray release];
_myArray = [[NSMutableArray alloc] initWithArray:[myString componentsSeparatedByString:@"\n"]];