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__) */
URL接続.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
。