0

我有一个子类:

#import <Foundation/Foundation.h>

@interface CustomURLConnection : NSURLConnection <NSURLConnectionDelegate>

@end

在它的实现文件中,我具有以下功能:

-(void) connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    NSLog(@"Authenticating from subclass.");

}

请注意,这didReceiveAuthenticationChallengeNSURLConnectionDelegate

这个片段目前在每个发送NSURLRequestusing的类中NSURLConnection

-(void) connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    // Code to authenticate ourselves.        
}

实际问题:

我希望子类具有预先确定的行为

 connection:(CustomURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge

而不必在每个类中实现该功能。而是让每个类都使用子类,并让子类自动处理每个身份验证挑战。

班级分配如下:

cUrlConnection = [[CustomURLConnection alloc]initWithRequest:req delegate:self   startImmediately: YES];
if (cUrlConnection)
{
   // Handle events when connection is active.
}

如果有人对我如何CustomURLConnection处理身份验证机制和/或提示/指针有任何见解,我会很高兴。

4

1 回答 1

0

这是一个有点尴尬的模式,但是您想要在子类中做的是接管委托设置/获取,并为超类提供一个不同的私有实现委托,以您想要的方式实现此方法并传递所有其他方法给用户提供的委托。(注意:因为NSURLConnection在初始化时接受它的委托,所以没有-delegate-setDelegate:方法可以覆盖。这是未经测试的,但它可能看起来像这样:

@interface MyCustomURLConnection : NSURLConnection
@end

@interface MyPrivateImpDelegate : NSObject
- (id)initWithRealDelegate: (id<NSURLConnectionDelegate>)realDel;
@end

@implementation MyPrivateImpDelegate
{
    __weak id<NSURLConnectionDelegate> _userDelegate;
}

- (id)initWithRealDelegate:(id<NSURLConnectionDelegate>)realDel
{
    if (self = [super init])
    {
        _userDelegate = realDel;
    }
    return self;
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    // Your auth implementation here...

    // maybe call through if you want?
    if ([_userDelegate respondsToSelector: _cmd])
    {
        [_userDelegate connection:connection didReceiveAuthenticationChallenge:challenge];
    }
}

- (id)forwardingTargetForSelector:(SEL)aSelector
{
    return _userDelegate;
}

- (BOOL)respondsToSelector:(SEL)aSelector
{
    BOOL retVal = [super respondsToSelector: aSelector];
    if (!retVal)
    {
        retVal = [_userDelegate respondsToSelector: aSelector];
    }
    return retVal;
}

@end


@implementation MyCustomURLConnection
{
    MyPrivateImpDelegate* _fakeDelegate;
}

- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately
{
    MyPrivateImpDelegate* privDel = [[MyPrivateImpDelegate alloc] initWithRealDelegate: delegate];
    if (self = [super initWithRequest:request delegate:privDel startImmediately:startImmediately])
    {
        _fakeDelegate = privDel; // make sure our private delegate lives as long as we do.
    }
    return self;
}

- (void)dealloc
{
    _fakeDelegate = nil;
}

@end
于 2013-09-20T11:46:40.417 回答