简体   繁体   中英

iOS Delegate Issue with multiple view controllers

I have an app with two view controllers..the parent controller, and one that is pushed onto the stack the child one.

I have coded my program such that the networkClass's delegate is set to the parent OR child whenever the viewDidAppear method of either parent or child view is called.

Hence, the problem is, my child class has some delegate methods implemented that are not needed in the parent class as the parent class never makes some of these network calls. However, when I initiated a network call in the child class, and hit BACK to the parent class before it completes..the parent class is now set as the delegate.

But since the parent class does not have the delegate method implemented, it crashes.

Can I know a workaround?

Option 1: Cancel the operation in the child viewWillDisappear .

Option 2: In the networkClass , check that the method is implemented before calling it.

Option 3: (Code smell): Implement a stub in the parent.

You should probably cancel the operation (Op.1) in any case. If you marked the functions as optional in the protocol definition you should definitely check for its existence (Op.2); if not, you should have received a compiler warning about an incomplete implementation. Don't ignore any compiler errors, especially about unimplemented methods! If it doesn't make sense to implement them fully, you should seriously consider whether they should be optional (2). You can, of course, implement stubs ( -(void)callback1{} ), but that is rarely the correct course of action.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM