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()
阅读全文
0 0
- iOS NSthread & Thread 开启线程的几种方式
- NSThread 开启线程的集中方式
- android开启线程的几种方式
- ios关于线程调度的三种方式之NSThread
- NSThread创建线程的三种方式
- 多线程NSThread的简单创建和使用——创建线程的几种方式
- C# 开启线程几种方式
- NSThread类三种创建线程的方式
- ios线程篇:多线程的几种创建方式
- ios 几种线程依赖的处理方式
- 开启线程的几种方法使用
- 开启闪光灯的几种方式
- 线程THread的俩种创建方式
- iOS 之多线程 NSThread
- iOS NSThread线程
- IOS 多线程 线程NSThread
- IOS 多线程 线程NSThread
- IOS线程 NSThread
- matplotlib常用函数subplot
- 指针
- Android Studio 2.x com.android.tools.fd.runtime.IncrementalChange $change
- 常用的两种单例模式
- MySQL性能分析语句 show profile/show profiles
- iOS NSthread & Thread 开启线程的几种方式
- Deepmind星际争霸2平台使用第一轮-完成采矿
- 通向架构师的道路(第二天)之apache tomcat https应用
- public、protected、default、private作用域
- java使用pinyin4j生成拼音
- CommonJS与AMD的规范和兼容
- VTK学习-第一个多柱体生成
- Java基础-方法区以及static的内存分配图
- 数据库基本类型知识