多线程下的performSelector和NSThread的使用
2024-08-24 02:25:59
多线程下的performSelector和NSThread的使用
NSThread的多线程使用:
我们可以使用这两种方法来使用线程中的问题
- (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument
+ (void)detachNewThreadSelector:(SEL)aSelector toTarget:(id)aTarget withObject:(id)anArgument
第一个是实例方法,传统方法创建一个线程,这个方法必须要在调用了[thread start]的时候才可以运行。
第二个是类方法,创建了之后,会立即调用的。
1、[NSThread detachNewThreadSelector:@selector(selector) toTarget:self withObject:nil];
2、NSThread* myThread = [[NSThread alloc] initWithTarget:self
selector:@selector(selector)
object:nil];
[myThread start];
performSelector来调用多线程:
我们可以使用这两种方法来使用线程中的问题
[self
performSelector:@selector(selector)
onThread:[NSThread
mainThread] withObject:nil
waitUntilDone:YES];
[self
performSelectorInBackground:@selector(selector)
withObject:nil];
第一个为可以指定调用线程的方法。
第二个为可以指定在后台调用事件,线程系统分配的方法。
[self performSelector:@selector(performSelectorMethods) onThread:[NSThread mainThread] withObject:nil waitUntilDone:YES]; [self performSelectorInBackground:@selector(performselectorINbackgroud) withObject:nil];
下面是使用以上方法的范例:
@implementation NSThreadUSE - (void)viewDidLoad {
[super viewDidLoad]; // 使用传统方法创建一个线程。这个方法必须要在调用了[thread start]的时候才可以运行
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(initWithTargetMethods) object:nil];
[thread start]; // 使用类方法来调用线程,这个方式会立即调用并执行线程
[NSThread detachNewThreadSelector:@selector(detachNewThreadMethods) toTarget:self withObject:nil]; // 使用performSelector的方法来调用函数,并且设置调用方法的线程
[self performSelector:@selector(performSelectorMethods) onThread:[NSThread mainThread] withObject:nil waitUntilDone:YES]; // 使用performSelectorInBackground这个方法来被调用函数,这个函数是在后台调用的
[self performSelectorInBackground:@selector(performselectorINbackgroud) withObject:nil];
} #pragma mark NSThread Methods
-(void) initWithTargetMethods{
NSLog(@"initWithTargetMethods is ---------------%@", [NSThread currentThread]);
} -(void) detachNewThreadMethods{
NSLog(@"detachNewThreadMethods is ---------------%@", [NSThread currentThread]);
} -(void) performSelectorMethods{
NSLog(@"performSelectorMethods is ---------------%@", [NSThread currentThread]);
} -(void) performselectorINbackgroud{
NSLog(@"performselectorINbackgroud is ---------------%@", [NSThread currentThread]);
} @end
最新文章
- 思维导图FreeMind安装问题及简单使用
- css 让内容满屏居中不变形
- WCF服务在类库中的引用
- c#读取文本文档实践4-读入到list泛型集合计算后写入新文档
- iproute-2.6.32
- 《第一行代码--Android》阅读笔记之广播
- Enterprise Library 4 数据访问应用程序块
- [学习心得][Introduction to ASP.NET Core 1.0]3-2 ASP.NET Core and MVC Pattern
- OpenGL判断一个点是否可见
- linux指令(1)
- 洛谷 P2764 最小路径覆盖问题 解题报告
- pytest.11.生成xml格式的测试报告
- (转第二方案)在 ASP.NET 環境下使用 Memcached 快速上手指南
- Redis连接的客户端(connected_clients)数过高或者不减的问题解决方案
- 【Unity】9.1 导入粒子系统组件
- Java如何显示所有正在运行的线程?
- .NET中方法的注意事项 明细
- ExtJS学习------Ext.define的继承extend,用javascript实现相似Ext的继承
- Netbeans取消CTRL+\才能代码提示的方法
- 新疆大学ACM-ICPC程序设计竞赛五月月赛(同步赛)- XOR(二进制使用)