未调用 UIViewController 析构函数

UIViewController Destructor not being called

目前我有两个 UIViewControllers 叫做 FormAFormB

现在 FormA 调用 FormB(formA 中的 formB 属性 是非原子的并且是强的)

self.formB = [[ MediaPlayer alloc] initWithNibName:@"MediaPlayer" bundle:nil ];
//Pass some values to FormB (all of these fields are strong)
((formB*)self.formB).SongInProgress_Name= songName;
((formB*)self.formB).SongInProgress_Path= song_path;
((formB*)self.formB).MusicCollectionPath= self.ArraySongNamePath;
[self presentViewController:self.formB animated:TRUE completion:nil];

当 FormB 试图关闭时,它会返回到 FormA

[ ((FormA*)self.presentingViewController) BackHere];

现在回到 FormA。 FormA 试图以这种方式关闭 FormB

[self.presentedViewController dismissViewControllerAnimated:TRUE completion:nil];

self.formB = nil;

执行上述操作不会调用 FormB 中的析构函数,即

-(void)dealloc {

    /* Desructor*/
}

为什么析构函数没有被调用?

这可能不是问题的根源,但你应该永远不要这样做:

self.formB = [[ MediaPlayer alloc] initWithNibName:@"MediaPlayer" bundle:nil ];

保留对要显示的视图控制器的强引用不是你的事。视图层次结构将保留它。您不是所有者;视图层次结构是。所以你不能取得所有权。在创建和呈现视图控制器时将其设为 local 变量:

MediaPlayer* mp = [[ MediaPlayer alloc] initWithNibName:@"MediaPlayer" bundle:nil ];
mp.SongInProgress_Name = songName; // etc.
[self presentViewController:mp animated:TRUE completion:nil];

现在,正如我在开头所说的那样,这很重要,但它可能不是问题的根源。您的 MediaPlayer 实现中可能有一个保留周期 。但是你没有显示任何代码,所以我无从得知。为什么不使用 Instruments 和 Leaks 模板找出保留周期在哪里?

作为对 Matt 回答的补充,您的视图控制器很可能由于保留周期而未解除分配。这些是由彼此保持强引用的对象生成的,这在您没有正确解耦视图控制器时很常见,例如:

您可以通过将行 [((FormA*)self.presentingViewController) BackHere]; 更改为 [self.presentingViewController dismissViewControllerAnimated:YES completion:nil] 来优化您的代码。这允许你让 FormB 成为一个更抽象的视图控制器,可以从将来不是 FormA 的其他视图控制器中呈现,并且不需要将 FormB 作为变量存储在 FormA 中,增加了两者的解耦 类 并减少您无意中创建保留周期的机会。