用到的类是NSThread类,这里使用detachNewTheadSelector:toTagaet:withObject创建一个线程。
函数setupThread:(NSArray*)userInfor。通过userInfor将需要的数据传到线程中。
函数定义:
-(void)setupThread:(NSArray*)userInfor{
[NSThread detachNewThreadSelector:@selector(threadFunc:) toTarget:self withObject:(id)userInfor];
//这个函数就和pthread_create函数一样了,不过在有xib交互时不能直接使用pthread_create函数,因为pthread_create调用一个c函数(相当于这个selector),c函数里面不能调用xib的控件,这就是我遇到的问题,可能会有别的解决办法。
}
- (void)threadFunc:(id)userInfor{
NSAutoreleasePool*pool = [[NSAutoreleasePool alloc] init];
//。。。。需要做的处理。
//这里线程结束后立即返回
[self performSelectorOnMainThread:@selector(endThread) withObject:nil waitUntilDone:NO];
[pool release];
performSelectorOnMainThread通知主线程执行函数endThread。也可以使用performSelector:onThread:withObject:waitUntil 通知某线程执行线程结束后的处理。
线程内不要刷新界面。如果需要刷新界面,通过performSelectorOnMainThread,调出主线程中的方法去刷新。//哇塞这句话太关键了。。终于找到组织了
例如,启动一个线程下载图片://启动线程
[NSThread detachNewThreadSelector:@selector(downloadImage:) toTarget:self withObject:url];
//线程函数
//NSURL这个类,都有哪些用处》?
- (void) downloadImage:(NSString*)url{
_subThreed = [NSThread currentThread];
self.uploadPool = [[NSAutoreleasePool alloc] init];
self.characterBuffer = [NSMutableData data];
done = NO;
[[NSURLCache sharedURLCache] removeAllCachedResponses];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURLURLWithString:url]];
self.connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
[self performSelectorOnMainThread:@selector(httpConnectStart) withObject:nil waitUntilDone:NO];
if (connection != nil) {
do {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; //这个NSRunLoop貌似很有用
} while (!done);
}
self.photo = [UIImage p_w_picpathWithData:characterBuffer];
//下载结束,刷新(线程间通讯)
[self performSelectorOnMainThread:@selector(fillPhoto) withObject:nil waitUntilDone:NO];
// Release resources used only in this thread.
self.connection = nil;
[uploadPool release];
self.uploadPool = nil;
_subThreed = nil;