Through presenting new view controller viewWillDisappear on parent is triggered where I unsubscribe from the events

情到浓时终转凉″ 提交于 2019-12-11 04:07:18

问题


On my main view controller I have a button which shows another view controller, where some settings can be changed:

PresentViewController (new UINavigationController(anotherViewController), true, null);

For the dismiss of anotherViewController the parent should be responsible. I also have to know if something has changed (saved). Therefore I use events.

I'm attaching the event handlers in viewWillAppear on my parent view controller

anotherViewController.DismissMe += CancelEventHandler;
anotherViewController.SaveFilter += SaveEventHandler;

and in viewWillDisappear I'm unsubscribing from it

anotherViewController.DismissMe -= CancelEventHandler;
anotherViewController.SaveFilter -= SaveEventHandler;

Because viewWillDisappear is triggered when a new view controller is presented, I automatically unsubscribe from the events. When I want to fire the events in anotherViewController I can't, because no one is subscribed to my events.

I have to unsubscribe from the events, because otherwise the view controller is never released.

How can I solve this situation?


回答1:


My current solution looks like the following:

Before I present the new view controller I'm subscribing to the events for cancel and save (custom created events). Because the presenting view controller gets this events (cancel, save) when the presented view controller is closed or a save operation is done, I remove subscriptions to this events (cancel, save) when I retrieve one of those. Id est in the event handler itself I'm unsubscribing from the event.

With this it should be assured that I only subscribe one time and that I also unsubscribe when needed.

There are more approaches to this, which can be found in the comments to my question.



来源:https://stackoverflow.com/questions/32117567/through-presenting-new-view-controller-viewwilldisappear-on-parent-is-triggered

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!