线程创建与启动
NSThread的创建主要有两种直接方式:
[NSThread detachNewThreadSelector:@selector(myThredaMethod:) toTarget:self withObject:nil];CocoaLigature1
和
NSThread * myThread =[[NSThread alloc] initWithTarget:self selector:@selector(myThredaMethod:) object:nil];
[myThread start];CocoaLigature1
这两种方式的区别是:
前一种一调用就会立即创建一个线程来做事情;
而后一种虽然你 alloc 了也 init了,但是要直到我们手动调用 start 启动线程时才会真正去创建线程。
这种延迟实现思想在很多跟资源相关的地方都有用到。后一种方式我们还可以在启动线程之前,对线程进行配置,比如设置 stack 大小,线程优先级。
还有一种间接的方式,更加方便,我们甚至不需要显式编写 NSThread 相关代码,
那就是利用 NSObject 的类方法 performSelectorInBackground:withObject: 来创建一个线程:CocoaLigature0
[myobject performSelectorInBackground:@selector(myThredaMethod:) withObject:nil];
CocoaLigature1 其效果与 NSThread 的 detachNewThreadSelector:toTarget:withObject: 是一样的。
![[转载]iOS多线程学习笔记之二:线程创建与启动 [转载]iOS多线程学习笔记之二:线程创建与启动](http://s16.sinaimg.cn/middle/82569b61tb36be4b673ef&690)
@interface ThreadViewController : UIViewController {
UIProgressView *progressView;
UILabel *label;
NSThread *thr;
}
@property (nonatomic, retain) IBOutlet UIProgressView *progressView;
@property (nonatomic, retain) IBOutlet UILabel *label;
- (IBAction) startProgress:(id)sender;
@end
@implementation ThreadViewController
@synthesize progressView,label;
- (void)dealloc
{
[progressView release];
[label release];
[super dealloc];
}
- (void)viewDidUnload
{
[super viewDidUnload];
self.progressView = nil;
self.label = nil;
}
……
#define UPDATE_IN_MAINTHREAD 1
- (void) updateProgress:(id)arg
{
float currentValue = [progressView progress];
progressView.progress = currentValue + 0.01;
label.text = [NSString stringWithFormat:@".0f%%", progressView.progress*100];
NSLog(@"current value %f", currentValue);
}
- (void) beginDownload:(id)arg
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSLog(@"begin to download ");
for (int i = 0; i < 100; i++) {
[NSThread sleepForTimeInterval:0.2f];
#if UPDATE_IN_MAINTHREAD
[self performSelectorOnMainThread:@selector(updateProgress:) withObject:nil waitUntilDone:NO];
#else
[self updateProgress:nil];
#endif
}
[pool release];
}
- (IBAction) startProgress:(id)sender
{
progressView.progress = 0.0f;
label.text = [NSString stringWithFormat:@".0f%%", progressView.progress*100];
NSLog(@"start progress");
#if 0
[NSThread detachNewThreadSelector: @selector(beginDownload:) toTarget:self withObject:nil];
#else
thr = [[NSThread alloc] initWithTarget:self selector:@selector(beginDownload:) object:nil];
[thr start];
#endif
}
@end