我遇到了一个不会上传的 Objective-C 上传器类的问题(未调用失败/成功委托并且服务器显示没有传入请求),除非我有一个自旋循环。它与旋转循环完美配合。
我是 Objective-C 的新手,设置如下:主应用程序实例化一个 C++ 类 (cppClass),该类在单独的 pThread 中运行一个静态函数 (cppFuncA)。
静态函数 (cppFuncA) 实例化一个 Objective-C 类/对象 (UploadFunc),它获取一些数据并上传它。
CppClass {
static void cppFuncA (...);
}
cppFuncA(...) {
UploadFunc* uploader = [[[UploadFunc alloc] retain] init];
while (condition) {
...
[uploader uploadData:(NSData*)data];
}
[uploader release]
}
上传者.h
@interface UploadFunc : NSObject
{
bool conditional;
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
- (void) uploadData:(NSData*)data;
@end
上传者.mm
@implementation UploadFeedback
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
conditional = false;
[connection release];
NSLog(@"Connection failed! Error - %@ %@",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
conditional = false;
NSLog(@"Succeeded! Received %d bytes of data",0);
[connection release];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"Response=%@", response);
}
-(void) uploadData:(NSData*)data
{
…
NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:theURL];
… construct request …
NSURLConnection* theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
// Only works if I have this following spin loop
conditional = true;
while(conditional) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
if (!theConnection) std::cerr << "Connection to feedback failed\n";
}
最后一个函数“-(void) uploadData:(NSData*)data”是我遇到问题的地方。如果没有自旋循环,它将无法工作。关于发生了什么的任何想法?
我在 NSURLRequest 和 NSURLConnection 中添加了保留,所以我认为它不是一个没有复制请求的竞争条件。
编辑:我觉得这些可能是类似的问题: NSURLConnection - 如何等待完成 和从后台线程到服务器的异步请求 但是我的对象(UploadFunc)即使在函数完成并超出范围后仍然存在......