我应该“拉起”重构

时间:2011-08-19 21:22:29

标签: objective-c refactoring

我有一些非常小的课程,我觉得应该“拉起来”,但方法太小,我不确定。例如,唯一有意义的不同是buildFromJSON:selector的主体。

我承认这类似于: Pull-up refactoring, Objective-C 但我觉得我的问题特定于重构非常小的类/方法。

另外,不确定它是否与我的特定代码示例相关,但我想知道子类是否符合协议,是否足以让它的父实际提供所需选择器的实现?

@implementation AsyncFoo

-(void)dealloc {
    [clientDelegate release];
    [super dealloc];
}

- (id)initWithDelegate: (id <ServiceClientProtocol>) delegate {
    if((self = [super init])) {
        clientDelegate = [delegate retain];
    }
    return self;
}

- (void)buildFromJSON:(NSString*)jsonResponseString {
    [clientDelegate serviceComplete:[RestAdapter buildFooArray: jsonResponseString]];
}

@end



@implementation AsyncBar

-(void)dealloc {
    [clientDelegate release];
    [super dealloc];
}

- (id)initWithDelegate: (id <ServiceClientProtocol>) delegate {
    if((self = [super init])) {
        clientDelegate = [delegate retain];
    }
    return self;
}

- (void)buildFromJSON:(NSString*)jsonResponseString {
    [clientDelegate serviceComplete:[RestAdapter buildBarArray:jsonResponseString]];
}

@end

包括代码示例在内的答案会很棒。

编辑:发布接受的答案我想补充一点,因为我能够进行子类化,派生类不需要声明它们符合协议:

@interface Async : NSObject <ModelBuilderProtocol> {
    id <ServiceClientProtocol> clientDelegate;
}
- (void)buildFromJSON:(NSString*)jsonResponseString;
@end

@interface AsyncArtistById : Async
@end 

1 个答案:

答案 0 :(得分:1)

您通常不会保留您的代理人,因为这会导致保留周期。

通过查看你的例子知道我所知道的,我可能会这样实现:

超级

// Async.h
@interface Async : NSObject

@property (nonatomic, assign) id<ServiceClientProtocol> delegate;

- (void)buildFromJSON:(NSString *)jsonResponseString;

@end

// Async.m
@implementation Async

@synthesize delegate = _delegate;

- (id)initWithDelegate:(id<ServiceClientProtocol>)delegate 
{
    self = [super init];
    if(self) {
        _delegate = delegate;
    }
    return self;
}

- (void)buildFromJSON:(NSString *)jsonResponseString
{
    // This will ensure that we over ride this method in a sub class
    [NSException raise:NSInternalInconsistencyException 
        format:@"You must override %@ in a subclass", NSStringFromSelector(_cmd)];
}

@end

具体子类AsyncFoo

// AsyncFoo.h
@interface AsyncFoo : Async
@end

// AsyncFoo.m
@implementation AsyncFoo

- (void)buildFromJSON:(NSString *)jsonResponseString 
{
    [self.delegate serviceComplete:[RestAdapter buildFooArray: jsonResponseString]];
}

@end

具体子类AsyncBar

// AsyncBar.h
@interface AsyncBar : Async
@end

// AsyncBar.m
@implementation AsyncBar

- (void)buildFromJSON:(NSString *)jsonResponseString {
    [self.delegate serviceComplete:[RestAdapter buildBarArray:jsonResponseString]];
}

@end