應用中有兩個類都要執行protocol協議
能不能在一個類中執行另一個類的協議,然後再反過來執行?
會不會引起錯誤?
主要問題是循環依賴,你可以把協議分離出來放到每天頭文件裡:
ClassA.h:
#import <Foundation/Foundation.h>
#import "ClassBProtocol.h"
@interface ClassA : NSObject <ClassBProtocol>
@end
ClassB.h:
#import <Foundation/Foundation.h>
#import "ClassAProtocol.h"
@interface ClassB : NSObject <ClassAProtocol>
@end
ClassAProtocol.h:
#import <Foundation/Foundation.h>
@protocol ClassAProtocol <NSObject>
...
@end
ClassBProtocol.h:
#import <Foundation/Foundation.h>
@protocol ClassBProtocol <NSObject>
...
@end
第二種方法這樣:
ClassA.h:
#import <Foundation/Foundation.h>
@interface ClassA : NSObject
@end
ClassA.m:
#import "ClassA.h"
#import "ClassB.h"
@implementation ClassA () <ClassBProtocol>
@end
@implementation ClassA
@end
ClassB.h:
#import <Foundation/Foundation.h>
@interface ClassB : NSObject
@end
ClassB.m:
#import "ClassB.h"
#import "ClassA.h"
@implementation ClassB () <ClassAProtocol>
@end
@implementation ClassB
@end