iOS多线程编程(一)NSThread

最后更新于:2022-04-01 22:59:00

## @NSThread的使用 ### 1.显示调用的类为NSThread有两种直接创建方式: **- (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument(手动开启)** **+ (void)detachNewThreadSelector:(SEL)aSelector toTarget:(id)aTarget withObject:(id)anArgument(自动开启)** ~~~ 1、[NSThread detachNewThreadSelector:@selector(doSomething:) toTarget:self withObject:nil]; 2、NSThread* myThread = [[NSThread alloc] initWithTarget:self selector:@selector(doSomething:) object:nil]; [myThread start]; ~~~ ### 2\. 不显式创建线程的方法: **通过NSObject的Category方法调用:** **- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait; //在主线程中运行方法,wait表示是否阻塞这个方法的调用,如果为YES则等待主线程中运行方法结束。一般可用于在子线程中调用UI方法。** **- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thread withObject:(id)arg waitUntilDone:(BOOL)wait;** //**在指定线程中执行,但该线程必须具备run loop。** **- (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg;** //产生新线程。 **3.NSThread的其它一些常用的方法** **1. + (NSThread *)currentThread; //获得当前线程** **2. + (void)sleepForTimeInterval:(NSTimeInterval)ti; //线程休眠** **3. + (NSThread *)mainThread; //主线程,亦即UI线程了** **4. - (BOOL)isMainThread; + (BOOL)isMainThread; //当前线程是否主线程** **5. - (BOOL)isExecuting; //线程是否正在运行** **6. - (BOOL)isFinished; //线程是否已结束** **7.- (void)cancel  // 终止线程循环** **8.- (void)start  // 开启线程循环**
';