首页 > 代码库 > NSThread学习
NSThread学习
使用多线程可以防止主线程阻塞。同时也可以将一个大的任务分成若干个小的任务去做。
常用方法一:
1, 首先使用 detachNewThreadSelector:toTarget:withObject:来启动一个新的线程
[NSThread detachNewThreadSelector:@selector(addImagesWithPaths:) toTarget:self withObject:urls];
2,在上面执行的函数中需要首先使用新的NSAutoreleasePool来管理内存,因为在线程函数中创建的任何对象在函数执行完成以后并不会得到释放,会造成内存泄漏。形式为:
- (void)addImagesWithPaths:(NSArray *)urls
{
NSInteger i, n;
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[urls retain];
n = [urls count];
for ( i= 0; i < n; i++)
{
NSURL *url = [urls objectAtIndex:i];
[self addImagesWithPath:[url path] recursive:NO];
}
/* update the datasource in the main thread */
[self performSelectorOnMainThread:@selector(updateDatasource) withObject:nil waitUntilDone:YES];
[urls release];
[pool release];
}
3, performSelectorOnMainThread 更新主界面
- (void)updateDatasource
{
//-- update our datasource, add recently imported items
[_images addObjectsFromArray:_importedImages];
//-- empty our temporary array
[_importedImages removeAllObjects];
//-- reload the image browser and set needs display
[_imageBrowser reloadData];
}
常用方法二:
1,NSThread* myThread = [[NSThread alloc] initWithTarget:self selector:@selector(doSomething:) object:nil]; //创建thread
2,[myThread start]; //启动一个thread
3,上锁比如典型的购票程序
NSLock *theLock;
- (void)run{ while (TRUE) {
// 上锁 [theLock lock]; if(tickets >= 0){
[NSThread sleepForTimeInterval:0.09];
count = 100 - tickets;
NSLog(@"当前票数是:%d,售出:%d,线程名:%@",tickets,count,[[NSThread currentThread] name]);
tickets--;
}else{
break;
}
[theLock unlock];
}
}