我不明白爲什麼我必須在Objective-C中執行以下操作。我有興趣發現爲什麼在一般意義上(即爲什麼語言/編譯器迫使我這樣做),也許發現替代方案,我已經拿出:爲什麼我的ObjC實現類#import實現協議的_interface_?
我有一個協議:
// (file: MyObserver.h)
@class TheObserved;
@protocol MyObserver <NSObject>
- (void)itWasObserved:(TheObserved *)observedInstance;
@end
有「TheObserved」即(週期地)的接口,使用的協議:
// (file: TheObserved.h)
@protocol MyObserver;
@interface TheObserved : NSObject
@property id <MyObserver> myObserver;
- (void)lookAtThisData:(NSString *)someData withObserver:(id <MyObserver>)observer;
@end
這就是說,你可以看到,該協議有一個消息,其接受一個實例的接口,並且接口有一個方法需要一個實例實現協議。
在我的接口的實現:
// (file: TheObserved.m)
#import "TheObserved.h"
#import "MyViewController.h" // <-- note this import
@implementation TheObserved
@synthesize myObserver;
- (void)lookAtThisData:(NSString *)someData withObserver:(id <MyObserver>)observer {
self.myObserver = observer;
// some asynchronous looking at the data is done here.
}
- (void)asynchCallback:(NSData *) data {
// check if the data is as we expect, if so ..
[self.myObserver itWasObserver: self]
}
@end
MyViewController.h實現協議:
// (file: MyViewController.h)
#import <UIKit/UIKit.h>
#import "OWLMorphDataObserver.h"
@interface MyViewController : UITableViewController <MyObserver>
@end
,並在其執行:
// (file: MyViewController.m)
#import "TheObserved.h"
@interface MyViewController() {
@property TheObserved *observed;
@end
@implementation MyViewController
@synthesize observed;
- (void) aMethod:(NSString *)dataString {
[self.observed lookAtThisData:dataString withObserver:self]
}
@end
我的問題是:爲什麼,在我的Observed類中,我需要#導入實現了@protocol的「MyViewController.h」,甚至是儘管具體實現從未在Observed類中明確引用?如果我不這樣做,我得到和編譯錯誤:當然,我想有多個不同的視圖控制器實現此協議的
no known instance method for selector 'lookAtThisData:'
這裏的問題是,。那麼爲什麼我不得不導入其中的一個來編譯它?
有沒有另一種方法可以構造此代碼以獲得所需的效果,而不需要在想要使用它的類中導入協議的具體實現?
你能命名包含每個代碼段的文件嗎?例如「我有一個協議」添加「在foo.h中定義」。 – danh
當然,我做到了。 – scot
錯誤消息與您發佈的代碼不匹配。 '-lookAtThisData:'和'-lookAtThisData:withObserver:'是兩種不同的方法。否則,您發佈的代碼是正確的。 '-lookAtThisData:withObserver:'在TheObserved.h中聲明,並且這是您需要導入以調用該方法的頭。 – Darren