没有办法直接实现Objective-C
委托方法C++
。您真正希望做的最好的事情是使用实例变量Objective-C++
创建一个C++
对象,该实例变量是一个 Objective-C 对象,其唯一目的是成为NSURLConnection
委托并将这些方法调用转发给拥有C++
对象。C++
对象应拥有/保留Objective-C
对象,并负责将其作为对象的委托插入NSURLConnection
。
上述模式的一个极其幼稚的实现可能如下所示:
URLConnection.h
#ifndef __Cplusplus__URLConnection__
#define __Cplusplus__URLConnection__
#include <string>
class URLConnection
{
public:
URLConnection(std::string url);
~URLConnection();
void DidReceiveResponse(const void* response);
void DidReceiveData(const void* data);
void DidFailWithError(std::string error);
void DidFinishLoading();
void* mNSURLConnection;
void* mDelegate;
};
#endif /* defined(__Cplusplus__URLConnection__) */
URLConnection.mm
#include "URLConnection.h"
@interface PrivateNSURLConnectionDelegate : NSObject <NSURLConnectionDelegate>
{
URLConnection* mParent;
}
- (id)initWithParent: (URLConnection*) parent;
@end
@implementation PrivateNSURLConnectionDelegate
- (id)initWithParent: (URLConnection*) parent
{
if (self = [super init])
{
mParent = parent;
}
return self;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
mParent->DidReceiveResponse(response);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
mParent->DidReceiveResponse(data.bytes);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
mParent->DidFailWithError(std::string([[error description]UTF8String]));
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
mParent->DidFinishLoading();
}
@end
URLConnection::URLConnection(std::string url)
{
this->mDelegate = [[PrivateNSURLConnectionDelegate alloc] initWithParent: this];
NSURLRequest* req = [NSURLRequest requestWithURL: [NSURL URLWithString: [NSString stringWithUTF8String: url.c_str()]]];
this->mNSURLConnection = [[NSURLConnection alloc] initWithRequest: req delegate: (id)this->mDelegate];
}
URLConnection::~URLConnection()
{
[(NSObject*)this->mNSURLConnection release];
[(NSObject*)this->mDelegate release];
}
void URLConnection::DidReceiveResponse(const void* response)
{
// Do something...
}
void URLConnection::DidReceiveData(const void* data)
{
// Do something...
}
void URLConnection::DidFailWithError(std::string error)
{
// Do something...
}
void URLConnection::DidFinishLoading()
{
// Do something...
}
归根结底,NSURLConnection
是一个Objective-C
对象。如果不使用Objective-C
.