在目标c中交换对象

时间:2012-08-08 05:24:20

标签: objective-c xcode oop object ownership

我试图在按钮操作时交换两个对象,但我无法让它工作。它是第一次交换,但下次点击按钮时,它会与EXC_BAD_ACCESS崩溃。

这是代码

-(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];

}

我在Search DTO(searchDTO)中从DTO和toDTO分配。

1 个答案:

答案 0 :(得分:4)

如果您不使用ARC,则在将tempDto设置为其他内容之前,您需要保留searchDTO.toDTO;否则旧值可能会被取消分配,您将在tempDto中有一个悬空引用。它应该是这样的:

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

或者像这样:

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