当我分离包含在 TableView 和 TableViewDataSource 文件中的 ViewController 时, 我收到运行时错误:“..EXC_BAD_ACCESS ..”。
下面有完整的源代码。
// ViewController file
<ViewController.h>
@interface ViewController : UIViewController <UITableViewDelegate>
@property (strong, nonatomic) UITableView *tableView;
@end
<ViewController.m>
- (void)viewDidLoad
{
**DS1 *ds = [[DS1 alloc] init];**
_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 100, 320, 200) style:UITableViewStylePlain];
_tableView.delegate = self;
**_tableView.dataSource = ds;**
[self.view addSubview:_tableView];
}
// TableViewDataSource file
<DS1.h>
@interface DS1 : NSObject <UITableViewDataSource>
@property (strong, nonatomic) NSArray *dataList;
@end
<DS1.m>
#import "DS1.h"
@implementation DS1
@synthesize dataList = _dataList;
- (id)init
{
self = [super init];
if (self) {
_dataList = [NSArray arrayWithObjects:@"apple",@"banana", @"orange", nil];
}
return self;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [_dataList 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];
}
cell.textLabel.text = [_dataList objectAtIndex:indexPath.row];
return cell;
}
@end
如果我从
更改 ViewController.m 的代码 _tableView.dataSource = ds;
到
_tableView.dataSource = self;
,那就好了。 (当然,在 DataSource 方法被附加到 ViewController.m 之后)
我找不到任何问题,请帮助我并提前致谢。
最佳答案
如果这是 ARC,您必须为数据源创建实例变量或 @property
。
您将 dataSource ds
分配为局部变量。但是tableView的dataSource
属性没有保留ds
。所以在 viewDidLoad
结束时,ARC 将释放 ds
并且它被释放。
将 ds 保存为您的 viewController 的属性。像这样:
@interface ViewController : UIViewController <UITableViewDelegate>
@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) DS1 *dataSource;
@end
- (void)viewDidLoad
{
[super viewDidLoad]; // <-- !!!
self.dataSource = [[DS1 alloc] init];
_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 100, 320, 200) style:UITableViewStylePlain];
_tableView.delegate = self;
_tableView.dataSource = self.dataSource;
[self.view addSubview:_tableView];
}
关于iphone - TableViewDataSource 文件的运行时错误已分离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9835645/