ios开发答疑录系列---(七)IOS 线程处理
来源:互联网 发布:sqlserver教程 编辑:程序博客网 时间:2024/06/11 13:05
============================================================
博文原创,转载请声明出处
电子咖啡(原id蓝岩)
============================================================
IOS中,如果要在主线程中启动一个子线程,可以又两种方法:[NSThread detachNewThreadSelector:@selector(myThreadMainMethod:) toTarget:self withObject:nil];这是在cocoa早期提供的方法,因此你可以在任何版本的ios和mac上调用此方法。
在 OS X v10.5(or later)和IOS中,苹果又提供了一种方法,可以允许你获得你的thread句柄,并且更方便的让主线程控制子线程。
NSThread* myThread = [[NSThread alloc] initWithTarget:self selector:@selector(myThreadMainMethod:) object:nil];[myThread start]; // Actually create the thread
如果要停止子线程,有两种方法:
第一种,是在子线程中执行:
[NSThread exit];
另一种是在主线程执行:
[myThread cancel];要注意的是,[mThread cancel]; 并不能exit线程,只是标记为canceled,但线程并没有死掉。加入你在子线程中执行了一个循环,则cancel后,循环还在继续,你需要在循环的条件判断中加入 !mThread.isCancelled 来判断子线程是否已经被cancel来决定是否继续循环。
下面是我的一个测试demo,可以参考一下:
@synthesize mThread;- (void)viewDidLoad{ [super viewDidLoad]; NSLog(@"main thread:%@",[NSThread currentThread]); mThread=[[NSThread alloc] initWithTarget:self selector:@selector(subThreadMethod) object:nil]; [NSThread detachNewThreadSelector:@selector(performMethod) toTarget:self withObject:nil]; }-(void)subThreadMethod{ int i=1; while (i++>0 && ![[NSThread currentThread]isCancelled]) { NSLog(@"subthread i:%d ,thread:%@",i,[NSThread currentThread]); } }- (IBAction)startThread:(id)sender { NSLog(@"startThread...."); [mThread start];}- (IBAction)stopThread:(id)sender { NSLog(@"mThread.isCancelled: %d",mThread.isCancelled); if (!mThread.isCancelled) { [mThread cancel];// [mThread exit]; //exit 是类方法,不可以用在对象上 }}- (IBAction)performOnSubThread:(id)sender { //在子线程调用方法 [self performSelector:@selector(performMethod) onThread:mThread withObject:nil waitUntilDone:NO];}-(void)performMethod{ NSLog(@"performMethod.... thread:%@",[NSThread currentThread]); }@end
- ios开发答疑录系列---(七)IOS 线程处理
- ios开发答疑录系列---(七)IOS 线程处理
- ios开发答疑录系列--XCode重命名文件夹
- ios开发答疑录系列--关于IOS单利的思考
- ios开发答疑录系列---(一)Android和IOS图片编码之跨平台传递
- ios开发答疑录系列---xcode 经常crash 当使用svn时候
- ios开发答疑录系列---(六)NSString和NSData通过Base64编码的相互转换
- ios开发答疑录系列---Xcode 4 设置App版本号
- ios开发答疑录系列---(五)NSString 和NSCharacterset的不同之处
- ios开发答疑录系列---(三)C/C++ 数组的初始化
- ios开发答疑录系列---(二)Xcode 提交过程 遇到 no identities were available
- ios开发答疑录系列---iphone & ipad 图标大小和xcode配置
- ios开发答疑录系列---xcode release 和 debug 模式造成的不同
- ios开发答疑录系列---Xcode 4 设置App版本号
- ios开发答疑录系列---(二)Xcode 提交过程 遇到 no identities were available
- ios开发答疑录系列---xcode release 和 debug 模式造成的不同
- ios开发答疑录系列---xcode release 和 debug 模式造成的不同
- ios开发答疑录系列---(四)OS开发中混合使用ARC和非ARC项目
- struts2漏洞原理及解决办法
- C#操作注册表全攻略
- cocos2d-x实现贪食蛇游戏-沈大海cocos2d-x教程18
- 开源硬件成就未来新山寨
- 13-5 初级银行系统(2)
- ios开发答疑录系列---(七)IOS 线程处理
- 摩托罗拉各地网站被关闭
- 【web】赵雅智_jdbc开发
- Windows 8“死期”已定:2018年1月
- 多家互联网企业涉足电视机顶盒:不惧政策风险
- 常见的图片文件格式及各自的特点
- RedMonk 9月份编程语言排行
- ios中@class和 #import,两种方式的讨论
- 回调函数的使用封装(支持全局函数,类静态函数,类成员函数)