我在objective-c中使用工厂模式,但由于某种原因它从不调用子类的方法。我将通过代码解释:
// MailBoxViewController.m -- file using the factory:
SearchWorker* searchWorker = [SearchWorkerFactory getSearchWorker:param];
// whenever I call this method, it's always the one belonging to SearchWorker,
// rather than any of it's children classes, even if on breakpoint here, searchWorker
// is of class type AllSearchWorker
[searchWorker search:[searchParams objectForKey:@"query"] withDelegate:self withSnippedDelims:snippetDelims startWithDB:dbNum];
// searchWorkerFactory.m
#import "SearchWorkerFactory.h"
#import "SearchWorker.h"
#import "AllSearchWorker.h"
@implementation SearchWorkerFactory
+(id)getSearchWorker:(SearchWorkerType)syncType {
if (syncType == SearchWorkerTypeAll) {
AllSearchWorker* searchWorker = [[AllSearchWorker alloc] init];
return searchWorker;
}
return nil;
}
@end
// SearchWorker.h
@interface SearchWorker : NSObject
-(void)search:(NSString *)query withDelegate:(id)delegate withSnippedDelims:(NSArray *)snippedDelims startWithDB:(int)dbIndex;
@property (assign) volatile BOOL cancelled; // flag for when we cancel a search op
@property (nonatomic,readwrite,retain) NSOperationQueue *operationQueue;
@end
// SearchWorker.m
@implementation SearchWorker
..
-(void)search:(NSString *)query withDelegate:(id)delegate withSnippedDelims:(NSArray *)snippedDelims startWithDB:(int)dbIndex {
[NSException raise:NSInternalInconsistencyException
format:@"You must override %@ in a subclass", NSStringFromSelector(_cmd)];
}
@end
// AllSearchWorker.h
@interface AllSearchWorker : SearchWorker
-(void)search:(NSString *)query withDelegate:(id)delegate withSnippetDelims:(NSArray *)snippetDelims startWithDB:(int)dbIndex;
@end
// AllSearchWorker.m
@implementation AllSearchWorker
..
- (void)search:(NSString*)query withDelegate:(id)delegate withSnippetDelims:(NSArray *)snippetDelims startWithDB:(int)dbIndex {
// implementation
}
@end
所以我总是收到错误消息:
* 由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“您必须在子类中覆盖 search:withDelegate:withSnippedDelims:startWithDB:”*首先抛出调用堆栈:
知道为什么会这样吗?另外,如果我控制单击该方法search:withDelegate:withSnippedDelims:startWithDB
,xcode 会立即跳转到SearchWorker.m
(即它没有给我一个存在此方法的文件列表).. 如果我从中删除该方法SearchWorker.m
,它会抱怨该方法不存在。 . 想法?