简体   繁体   中英

Conflict between a tableView index and NSArray objectAtIndex

I'm implementing a TableView (class ListeExercice), showing a list of customized cells. These cells are defined in another class (class ExerciceTableCell).

In the class ListeExercice, I do create an NSArray as follow in the viewDidLoad method:

table1 = [NSArray arrayWithObjects:@"exo1", @"exo2", nil];
table2 = [NSArray arrayWithObjects:@"10:00", @"10:00", nil];

Then in the same class, I do everything in order to display the cells in the table

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection(NSInteger)section
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView

The problem I got happens ins the following method, basically where the code in order to display the right cell is located :

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *exerciceTableIdentifier = @"ExerciceTableCell";
ExerciceTableCell *cell = (ExerciceTableCell *)[tableView dequeueReusableCellWithIdentifier:exerciceTableIdentifier];
if (cell == nil) 
{
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ExerciceTableCell" owner:self options:nil];
    cell = [nib objectAtIndex:0];
} 

//label1 is a label from the cell defined in the ExerciceTableCell class.

cell.label1.text = [tableIntituleExercice objectAtIndex:indexPath.row];

return cell;

}

The problem is that I got a conflict between these 2 lines:

cell = [nib objectAtIndex:0];

and

cell.Label1.text = [table1 objectAtIndex:indexPath.row];

Apparently there is a conflict between the 2 "objectAtIndex". I do not have any warning, just an App crash, and a thread saying "Thread 1 : EXC_BAD_ACCESS (code = 1 ....)

Any advice on what I could do?

If you're not using ARC, it's a plain memory management error. You have to retain the two arrays in these lines:

table1 = [NSArray arrayWithObjects:@"exo1", @"exo2", nil];
table2 = [NSArray arrayWithObjects:@"10:00", @"10:00", nil];

Otherwise, the objects will have been released before tableView:cellForRowAtIndexPath: is being called. It's for errors like these that you should generally always use property setters to assign values to ivars/properties. The setters care about the proper memory management for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM