這個錯誤相當惱人:明明協議已經定義好了,編譯器卻說找不到。
cannot find protocol declaration for "RefreshAudioListViewDelegate"
假設有兩個類別互相引用。PlayerController.h 裡自訂了一個代理協議:
// PlayerController.h
#import "PlayerListViewController.h"
@protocol RefreshAudioListViewDelegate <NSObject>
- (void)updateCurrentPlayedAudio:(NSUInteger)currentPlayedIndex;
@end
@interface PlayerController : NSObject
// ...
@end
而 PlayerListViewController.h 宣告要遵循這個協議:
// PlayerListViewController.h
#import "PlayerController.h"
@class PlayerController;
@interface PlayerListViewController : UIViewController <RefreshAudioListViewDelegate>
{
PlayerController *playerController;
}
@end
關鍵在於 #import 是「文字層級的展開」,而展開順序會造成循環:
#import "PlayerController.h",於是跳進 PlayerController.h。#import "PlayerListViewController.h",編譯器再跳回 PlayerListViewController.h。@interface PlayerListViewController : UIViewController <RefreshAudioListViewDelegate>。最直接的做法是把 PlayerController.h 裡的 #import "PlayerListViewController.h" 刪掉。PlayerController 通常只需要持有一個符合協議的 delegate,並不需要知道對方的具體型別,因此改用前向宣告就夠了:
// PlayerController.h
@class PlayerListViewController; // 前向宣告,不引入完整定義
@protocol RefreshAudioListViewDelegate <NSObject>
- (void)updateCurrentPlayedAudio:(NSUInteger)currentPlayedIndex;
@end
@interface PlayerController : NSObject
@property (nonatomic, assign) id <RefreshAudioListViewDelegate> delegate;
@end
若 PlayerController 實在需要呼叫 PlayerListViewController 的方法,就把那個 #import 移到 PlayerController.m 裡——標頭檔只放宣告,實作檔才放相依,這是 Objective-C 的基本原則。
當協議被多個類別共用時,更乾淨的做法是抽出成獨立標頭:
// RefreshAudioListViewDelegate.h
@protocol RefreshAudioListViewDelegate <NSObject>
- (void)updateCurrentPlayedAudio:(NSUInteger)currentPlayedIndex;
@end
然後 PlayerController.h 與 PlayerListViewController.h 都只 import 這個小檔案,循環相依自然消失。
若只是宣告型別(屬性、參數、回傳值),一律用 @class 前向宣告,不要 #import。這麼做除了避免循環,還能減少編譯相依、加快建置速度。
把可疑的 #import 逐一註解掉再編譯,看錯誤是否消失,通常兩三次就能定位。另外,Product → Clean 之後重新建置也是必要的——有時候只是 Xcode 的前置處理快取造成的假錯誤。