2011-10-14 50 views
4

我在Cocoa Touch中有一個視圖控制器,用於檢測設備何時旋轉並在它具有的2個視圖控制器的視圖之間切換:橫向和縱向。目標C和可可觸摸中的循環導入問題

我想在它的UIViewControllers能夠訪問FRRRotatingViewController,以類似的方式,因爲所有UIViewControllers可以訪問他們所在的UINavigationController

所以我創建了一個UIViewController子類(FRRViewController),將有一個rotatingViewController屬性。

我也修改了FRRRotatingViewController,所以需要FRRViewControllers而不是普通的UIViewControllers

不幸的是,當我在FRRViewController.h(反之亦然)中包含FRRRotatingViewController.h時,我似乎陷入了循環導入問題。我不知道如何解決它。有什麼建議麼?

下面的代碼:

// 
// FRRViewController.h 

#import <UIKit/UIKit.h> 
#import "FRRRotatingViewController.h" 

@interface FRRViewController : UIViewController 

@end 

// 
// FRRRotatingViewController.h 

#import <UIKit/UIKit.h> 
#import "FRRViewController.h" 

@class FRRRotatingViewController; 


@protocol FRRRotatingViewControllerDelegate 

-(void) FRRRotatingViewControllerWillSwitchToLandscapeView: (FRRRotatingViewController *) sender; 
-(void) FRRRotatingViewControllerWillSwitchToPortraitView: (FRRRotatingViewController *) sender; 

@end 


@interface FRRRotatingViewController : FRRViewController { 
    // This is where I get the error:Cannot find interface declaration for 
    // 'FRRViewController', superclass of 'FRRRotatingViewController'; did you 
    // mean 'UIViewController'? 
} 

@property (strong) UIViewController *landscapeViewController; 
@property (strong) UIViewController *portraitViewController; 

@property (unsafe_unretained) id<FRRRotatingViewControllerDelegate> delegate; 

-(FRRRotatingViewController *) initWithLandscapeViewController: (UIViewController *) landscape andPortraitViewController: (UIViewController *) portrait; 
-(void) deviceDidRotate: (NSNotification *) aNotification; 

@end 
+1

要在B中導入A,在B.h中添加@class A,並在B.m.中添加#import「A.h」。同樣的東西在A中導入B. – Jano

+1

爲什麼不用一個新的實現(例如FernardosViewController)來爲UIViewController子類化,這個實現包含了你希望在子類之間通用的任何方法?然後您將擁有FRRRotatingViewController和FRRViewController從FernardosViewController派生出來,並且您可以在.h文件中保持對彼此的引用(這將消除您的循環導入問題)。 –

+0

在FRRViewController中向FRRRotatingViewController添加一個前向聲明,並在FRRViewController.h中導入FRRViewController解決了它。編譯器不會接受一個超類,這是一個前向聲明。 – cfischer

回答

16

您可以使用正類和協議,聲明在標題在大多數情況下,避免圓形的導入問題,除了在繼承的情況下。在FRRViewController.h中,您是否可以不進行前向聲明,而不是導入FRRRotatingViewController.h

@class FRRRotatingViewController; 
4

如果我讀它的權利你的繼承結構是像這樣:

的UIViewController - > FRRViewController - > FRRRotatingViewController

但是你已經FRRViewController聲明依賴進口來自其子類FRRRotatingViewController的文件。因此,編譯器將在處理FRRViewController.h的其餘部分之前導入並讀取FRRRotatingViewController。

我假設你錯過了一些FRRViewController.h,因爲沒有任何旋轉視圖控制器在那裏的引用,但如果你在FRRRotatingViewController的.h中聲明瞭一個屬性,那麼你需要使用在FRRViewController.h向前聲明:中

@class FRRRotatingViewController 

代替

#import "FRRRotatingViewController.h" 

後者線,你可以把你的FRRViewController.m文件的第一行。