How do I resolve this circular dependency?

前端 未结 3 1438
遥遥无期
遥遥无期 2021-02-19 01:53

I\'m new to iOS development and am running into an issue with my header files. I\'m running into a circular dependency issue with my header files. My application delegate clas

相关标签:
3条回答
  • 2021-02-19 02:43

    @class is the syntactic approach you're looking for.

    Many coders look to avoid this circularity (which couples your classes in two directions, meaning your view controller can only be used in circumstances where the app delegate has that BOOL). There are a few ways you can do this:

    • Move the state variable to a singleton
    • Have the view controller fetch the value through an interface that the delegate implements
    • Key-Value Observing (which your app delegate would configure on your view controller)

    For small projects this kind of dependency is probably not really a problem, but as project size grows and the desirability of code reuse grows, clean functional separation becomes more and more valuable.

    0 讨论(0)
  • 2021-02-19 02:48

    Don't #import "MyViewController.h" in appDelegate.h. Instead, forward-declare the class.

    @class MyViewController;
    
    @interface appDelegate
    
         NSManagedObjectContext *managedObjectContext;
    
         MyViewController *viewController;
         BOOL myFlag;
    
    @end
    

    Also, you don't need to #import "appDelegate.h" in MyViewController.h if all you need is to reference the myFlag property in the implementation. Instead, import it in the MyViewController.m file.

    0 讨论(0)
  • 2021-02-19 02:57

    Did not read everything, but you can do forward declarations with @class. Usually how I solve circular dependencies.

    0 讨论(0)
提交回复
热议问题