1. 程式人生 > >iOS NSthread & Thread 開啟執行緒的幾種方式

iOS NSthread & Thread 開啟執行緒的幾種方式

一、開啟執行緒執行指定物件的方法

/**
 引數1: 執行引數2方法的物件
 引數2: 開啟執行緒後執行的方法
 引數3: 傳遞的物件資料(引數2的方法可以直接用)
 */
// OC
- (instancetype)initWithTarget:(id)target selector:(SEL)selector object:(id)argument;
類似的方法(分離): + (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(nullable id)argument;

// Swift
convenience init(target: Any, selector: Selector, object argument: Any?)
類似的方法(分離): class func detachNewThreadSelector(_ selector: Selector, toTarget target: Any, with argument: Any?)

OC程式碼:

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self demo1];
    // [self demo2];
}

// OC第一種方式, 需要手動開啟執行緒(可以獲取到執行緒物件, 如果無需對執行緒物件進行操作, 建議用下面第二種)
- (void) demo1 {
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(threadDemo:) object:@"baby"
]; [thread start]; } // OC第二種方式, 類方法實現, 不需要手動開啟 - (void) demo2 { [NSThread detachNewThreadSelector:@selector(threadDemo:) toTarget:self withObject:@"baby"]; } - (void)threadDemo:(id)parameter { NSLog(@"%@", parameter); }

Swift程式碼:

    override func touchesBegan(_ touches: Set<UITouch>
, with event: UIEvent?) { self.demo1() // self.demo2() } func demo1() { let thread = Thread.init(target: self, selector: #selector(threadDemo), object: "baby") thread.start() } func demo2() { Thread.detachNewThreadSelector(#selector(threadDemo), toTarget: self, with: "baby") } @objc func threadDemo(parameter: Any) { print(parameter) }

二、利用NSObject(NSThreadPerformAdditions) 的分類建立

/**
 引數1: 開啟執行緒後執行的方法
 引數2: 傳遞的物件資料(引數2的方法可以直接用)
 */
// OC
- (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg;
// Swift
func performSelector(inBackground aSelector: Selector, with arg: Any?)

OC程式碼:

[self performSelectorInBackground:@selector(demo:) withObject:@"baby"];

Swift程式碼:

self.perform(#selector(threadDemo), with: "name")

三、Block建立( iOS10.0之後出來的一個新方法 )

/**
 引數: 執行緒開啟之後執行的block
 */
// OC
- (instancetype)initWithBlock:(void (^)(void))block;
// Swift
convenience init(block: @escaping () -> Void)

OC程式碼:

NSThread *thread = [[NSThread alloc]initWithBlock:^{
        NSLog(@"begin thread");
    }];

[thread start];

Swift程式碼:

let thread = Thread.init {
            print("begin thread")
        }

thread.start()