iOS NSthread & Thread 开启线程的几种方式

来源:互联网 发布:linux搭建lnmp 编辑:程序博客网 时间:2024/05/24 07:25

一、开启线程执行指定对象的方法

/** 参数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;// Swiftconvenience 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;// Swiftfunc 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;// Swiftconvenience 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()
原创粉丝点击