线程创建:

准备在后台线程调用的方法 longOperation:

- (void)longOperation:(id)obj {
    NSLog(@"%@ - %@", [NSThread currentThread], obj);
}

方式1:alloc / init - start

NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(longOperation:) object:@"THREAD"];

[thread start];

[thread start];执行后,会在另外一个线程执行 longOperation: 方法

方式2:detachNewThreadSelector

[NSThread detachNewThreadSelector:@selector(longOperation:) toTarget:self withObject:@"DETACH"];

detachNewThreadSelector 类方法不需要启动,会自动创建线程并执行 @selector 方法

方式3:分类方法

[self performSelectorInBackground:@selector(longOperation:) withObject:@"PERFORM"];

// performSelectorInBackground 会自动在后台线程执行 @selector 方法

//分类API:
@interface NSObject (NSThreadPerformAdditions)
// equivalent to the first method with kCFRunLoopCommonModes
// 后台操作
- (void)performSelectorInBackground:(SEL)aSelector withObject:(nullable id)arg ;

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait modes:(nullable NSArray<NSString *> *)array;
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait;
// equivalent to the first method with kCFRunLoopCommonModes

- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait modes:(nullable NSArray<NSString *> *)array ;
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait ;
@end

当前线程

//获取当前线程
NSThread *t3 = [NSThread currentThread];

主线程

//获取主线程
[NSThread mainThread];

results matching ""

    No results matching ""