今天遇到一個棘手的問題:編譯時出現 cannot find protocol declaration for "RefreshAudioListViewDelegate" 的錯誤。
在 PlayerController.h 中自定義了一個代理 RefreshAudioListViewDelegate:
#import "PlayerListViewController.h"
@protocol RefreshAudioListViewDelegate <NSObject>
- (void)updateCurrentPlayedAudio:(NSUInteger)currentPlayedIndex;
@end
而在 PlayerListViewController.h 中又引入了 PlayerController.h,並讓類遵從該協議:
#import "PlayerController.h"
@interface PlayerListViewController : UIViewController <RefreshAudioListViewDelegate>
問題出在編譯順序上:
1. 編譯 PlayerListViewController.h 時,發現 #import "PlayerController.h",編譯器跑到 PlayerController.h。
2. 在 PlayerController.h 中又發現 #import "PlayerListViewController.h",編譯器又跑回 PlayerListViewController.h。
3. 當見到 @interface PlayerListViewController ... <RefreshAudioListViewDelegate> 這一句時,由於 PlayerController.h 中定義代理的語句還沒被載入,編譯器便報出找不到協議的錯誤。
這是一個典型的迴圈引用(互相 import)導致的問題。
刪除 PlayerController.h 中的 #import "PlayerListViewController.h",改用前向宣告(@class PlayerListViewController;)即可打破迴圈,錯誤便迎刃而解。