سؤال

I am trying to swap two objects upon a button action, but I can't get it to work. It's swapping on first time, but next time when I click on the button, it crashes with EXC_BAD_ACCESS.

Here's the code

-(IBAction)swapLocation
{
    CCLocDTO *tempDto = searchDTO.toDTO;
    searchDTO.toDTO = searchDTO.fromDTO;
    searchDTO.fromDTO = tempDto;

    NSLog(@"From Location is %@",searchDTO.fromDTO.streetAddress); //it becomes empty on next button click
    NSLog(@"To Location is %@",searchDTO.toDTO.streetAddress);
    NSLog(@"From Special Location is %@",searchDTO.fromSpecialDTO.locationName);
    NSLog(@"To Special Location is %@",searchDTO.toSpecialDTO.locationName);

    [self.tableView reloadData];

}

I am assigning fromDTO and toDTO in Search DTO(searchDTO).

هل كانت مفيدة؟

المحلول

If you are not using ARC, you need to retain tempDto before you set searchDTO.toDTO to something else; otherwise the old value may be deallocated, and you will have a dangling reference in tempDto. It should look like this:

CCLocDTO *tempDto = [searchDTO.toDTO retain];
searchDTO.toDTO = searchDTO.fromDTO;
searchDTO.fromDTO = [tempDto autorelease];

or like this:

CCLocDTO *tempDto = [searchDTO.toDTO retain];
searchDTO.toDTO = searchDTO.fromDTO;
searchDTO.fromDTO = tempDto;
[tempDto release];
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top