0

我正在尝试将我的 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];

4

1 回答 1

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"]];
于 2013-10-15T17:04:10.150 回答