我遇到了一个不会上传的 Objective-C 上传器类的问题(未调用失败/成功委托(delegate)并且服务器显示没有传入请求),除非我有一个自旋循环。它与旋转循环完美配合。
我是 Objective-C 的新手,设置如下:
主应用程序实例化一个在单独的 pThread 中运行静态函数 (cppFuncA) 的 C++ 类 (cppClass)。
静态函数 (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 - how to wait for completion
和 Asynchronous request to the server from background thread
但是,即使在函数完成并超出范围后,我的对象(UploadFunc)仍然存在......
最佳答案
不要在默认模式下运行你的运行循环。该框架可以将其他运行循环源置于默认模式,当您只想处理您的 NSURLConnection
时,它们将触发。 .诚然,框架在后台线程的运行循环上调度其他源应该是不常见的,但您不能确定。
运行运行循环不应该忙循环。除非数据传入的速度超出您的处理速度,否则您不应该提高 CPU 使用率。它似乎是忙循环的事实让我怀疑在默认模式下安排了另一个运行循环源。
安排NSURLConnection
在私有(private)运行循环模式下(只是您的应用程序独有的任意字符串),然后在该模式下运行运行循环。您可以使用 -initWithRequest:delegate:startImmediately:
初始化 NSURLConnection , 通过 NO
最后一个参数以避免在默认模式下调度。然后使用 -scheduleInRunLoop:forMode:
以您的私有(private)模式安排它。
关于c++ - NSURLConnection 在它自己的线程中没有旋转循环就不能工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10081985/