一个多线程函数:
[NSThread detachNewThreadSelector:@selecter(download:) toTarget:..... withObject:....];
在内部调用回调函数。在多线程之前,回调机制工作得很好,但是现在回调函数永远不会被调用。
我已经检查了线程函数是否工作。
代码如下,非常感谢。
+(void) download:(id) param{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
while(true){
NSLog(@"Thread going ");
NSArray* ary = [Data_Center sharedData_Center]->data;
for(int i = 0; i < [ary count]; i++) {
NSLog(@"code = %@", code);
..........
NSURL* url1 = [NSURL URLWithString:str_code];
[str_code length];
CFStreamClientContext dataStreamContext = {0, self, NULL, NULL, NULL};
CFHTTPMessageRef message = CFHTTPMessageCreateRequest(kCFAllocatorDefault, CFSTR("GET"), (CFURLRef)url1, kCFHTTPVersion1_1);
CFHTTPMessageSetBody(message, (CFDataRef)(CFSTR("")));
CFReadStreamRef readStream = CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, message);
CFOptionFlags events = kCFStreamEventHasBytesAvailable | kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered;
// print "client = 1" here
//NSLog(@"client = %d" , CFReadStreamSetClient(readStream, events, readStreamEventCallBack, & dataStreamContext));
if(CFReadStreamSetClient(readStream, events, readStreamEventCallBack, & dataStreamContext)) {
CFReadStreamScheduleWithRunLoop(readStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
}
CFReadStreamOpen(readStream);
}
[NSThread sleepForTimeInterval:10];
}
[pool release];
}
重要编辑:我下面的答案是不正确的,它实际上并没有在另一个线程中创建和运行读流!它似乎只是将读流安排在主线程中的运行循环上运行。
- 调用CFRunLoopGetCurrent ()
-
在获得新线程上的循环后调用CFRunLoopRun()
if(CFReadStreamSetClient(readStream, events, readStreamEventCallBack, & dataStreamContext)) { CFReadStreamScheduleWithRunLoop(readStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes); CFRunLoopRun(); }
是正确的代码!如果您希望在主线程的循环中运行代码,则只执行以下操作:
我发现你需要调用CFRunLoopGetMain()而不是CFRunLoopGetCurrent()
if(CFReadStreamSetClient(readStream, events, readStreamEventCallBack, & dataStreamContext)) {
CFReadStreamScheduleWithRunLoop(readStream, CFRunLoopGetMain(), kCFRunLoopCommonModes);}
在这种情况下,应该是正确的代码
请检查readStream是否打开
if (CFReadStreamOpen((CFReadStreamRef)readStream)) {
NSLog(@"CFReadStreamOpen Sucessfully");
}
else {
NSLog(@"Unable to start HTTP connection");
}
如果打开,试着评论NSAutoReleasePool我认为一些请求值在ReadStream打开之前被自动释放。
谢谢,
现在可以运行了
这很奇怪。回调永远不会被触发。相反,我可以在ReadStream打开后从原始函数读取数据。