I have a table that has its content filled using one of the two datasets provided based on the value of the segmented control attached. The data is pulled from the web.
The application crashes when I move back and forth between the two datasets and then select a table cell. The application works without hiccups when I use two separate table rather than a single table with a segmented control. Somehow combining them renders the application unstable.
One of the most error is when I tapped one the Acells of A table and while its loading I tapped the segment index=1, which will load B. it cause unrecognized selector being sent. meaning of the parameter o A table to being sent to B table.
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier0;
if (choice == 0) {
CellIdentifier0 = @"ACell";
} else if (choice == 1) {
CellIdentifier0 = @"BCell";
}
UITableViewCell *cell;
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier0];
if (cell == nil) {
if (choice == 0) {
[[NSBundle mainBundle] loadNibNamed:@"ACell" owner:self options:nil];
cell = ACell;
self.ACell = nil;
} else if (choice == 1) {
[[NSBundle mainBundle] loadNibNamed:@"BCell" owner:self options:nil];
cell = BCell;
self.BCell = nil;
}
}
if (choice == 0) {
[(ACell *)cell setA:(A*)[contentArray objectAtIndex:indexPath.row]];
} else if (choice == 1) {
[(BCell *)cell setB:(B*)[contentArray objectAtIndex:indexPath.row]];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if ( choice == 0) {
A = [contentArray objectAtIndex:indexPath.row];
[[NSNotificationCenter defaultCenter] postNotificationName:@"showA" object:A];
} else if (choice ==1) {
B = [contentArray objectAtIndex:indexPath.row];
[[NSNotificationCenter defaultCenter] postNotificationName:@"showB" object:B];
}
}
Assuming that
ACellhas the retained value when the nib file is loaded, doingself.ACell = nil;will release the older value and setACelltonil. Now the older value is the one pointed to bycell. So technically it would be pointing to junk as it would’ve been deallocated becauseACellis the only variable retaining the object. You can fix this by replacing,with,
As a sidenote, in the
didSelectRowAtIndexPath:method you’re doing} else if (choice = 1) {. Make sure you use==rather than=which will always evaluate to true along with changing the value ofchoicealthough it is unlikely in this case.