2012-03-23 4 views
1

TableView 및 TableViewDataSource 파일에 포함 된 ViewController를 분리하면 런타임 오류가 발생합니다 : "..EXC_BAD_ACCESS ..".TableViewDataSource 파일의 런타임 오류가 구분됩니다.

아래에는 전체 소스가 있습니다.

// 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 

나는 다음 괜찮아,

 _tableView.dataSource = self; 

 _tableView.dataSource = ds; 

에서 ViewController.m의 코드를 변경하는 경우. (물론, DataSource 메소드가 ViewController.m에 추가 된 후)

아무런 문제를 찾을 수 없으며, 사전에 감사드립니다.

답변

1

ARC 인 경우 dataSource에 인스턴스 변수 또는 @property을 만들어야합니다.
데이터 소스 ds을 로컬 변수로 할당합니다. 그러나 dataSource tableView의 속성은 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]; 
} 
+0

정말 고마워요. 괜찮습니다, 지금 – user1287710

+0

이것은 나를 미치게했습니다 ...이 충돌을 디버그 할 수있는 방법이 있습니까? – NSExplorer

관련 문제