如何解决此循环依赖? [英] How do I resolve this circular dependency?

查看:90
本文介绍了如何解决此循环依赖?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是iOS开发的新手,我遇到了头文件的问题。我的头文件遇到循环依赖问题。我的应用程序委托类包含一个指向我的视图控制器的指针,因为我必须在我的didFinishLaunchingWithOptions方法中设置一个视图控制器的属性...

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 class contains a pointer to my view controller, since I have to set one of the view controller's properties in my didFinishLaunchingWithOptions method...

//appDelegate.h     //DISCLAIMER: THIS IS UNTESTED CODE AND WRITTEN ON THE FLY TO ILLUSTRATE MY POINT
#import <UIKit/UIKit.h>
#import "MyViewController.h"

@interface appDelegate

     NSManagedObjectContext *managedObjectContext;

     MyViewController *viewController;
     BOOL myFlag;

@end

//appDelegate.m
@implementation appDelegate

- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
     viewController.managedObjectContext = self.managedObjectContext;
     .
     .
     .
}
@end

在我的视图控制器中,我引用了 myFlag属性,这是我的app委托......

And in my view controller, I reference the "myFlag" property, that's in my app delegate...

//MyViewController.h                                        
#import "appDelegate.h"     //<---circular dependency, causing "Expected specifier-qualifier-list before MyViewController" errors in my appDelegate header file

@interface MyViewController: UIViewController
{
     NSManagedObjectContext *managedObjectContext;
}
@end

//MyViewController.m
@import "MyViewController.h"

@implementation MyViewController

- (void)viewWillAppear:(BOOL)animated
{
     [super viewWillAppear:animated];

     ((appDelegate*)[[UIApplication sharedApplication] delegate]).myFlag = NO;
}

@end

但是为了访问我的app委托中的myFlag属性,我需要导入app delegate的头文件。这就是造成循环依赖的原因。不确定如何解决这个问题,有没有人碰到这个?

But in order to access the "myFlag" property in my app delegate, I need to import the app delegate's header file. This is what's causing the circular dependency. Not sure how to resolve this, has anyone run into this?

提前感谢您的帮助!

推荐答案

不要 #importMyViewController.h appDelegate.h 。相反,向前声明该类。

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

@class MyViewController;

@interface appDelegate

     NSManagedObjectContext *managedObjectContext;

     MyViewController *viewController;
     BOOL myFlag;

@end

此外,您不需要 #importappDelegate.h MyViewController.h 中,如果只需要引用 myFlag < 实施中的/ code>属性。而是在 MyViewController.m 文件中导入它。

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.

这篇关于如何解决此循环依赖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆