您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

排除 cannot find protocol declaration 的迴圈引用問題

編輯:iOS 開發綜合

這個錯誤相當惱人:明明協議已經定義好了,編譯器卻說找不到。

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 是「文字層級的展開」,而展開順序會造成循環:

  1. 編譯 PlayerListViewController.h,首先遇到 #import "PlayerController.h",於是跳進 PlayerController.h。
  2. 在 PlayerController.h 中,第一句又是 #import "PlayerListViewController.h",編譯器再跳回 PlayerListViewController.h。
  3. 由於 PlayerListViewController.h 已在處理中(被 #import 的檔案有 include guard 機制),這次展開被跳過,於是編譯器直接往下讀到 @interface PlayerListViewController : UIViewController <RefreshAudioListViewDelegate>。
  4. 此時 PlayerController.h 裡定義協議的那幾行還沒被讀到,編譯器自然報「找不到協議宣告」。

解法一:移除 PlayerController.h 中的互相 import

最直接的做法是把 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

若只是宣告型別(屬性、參數、回傳值),一律用 @class 前向宣告,不要 #import。這麼做除了避免循環,還能減少編譯相依、加快建置速度。

怎麼快速判斷是不是這個問題

把可疑的 #import 逐一註解掉再編譯,看錯誤是否消失,通常兩三次就能定位。另外,Product → Clean 之後重新建置也是必要的——有時候只是 Xcode 的前置處理快取造成的假錯誤。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved