代码改变世界

IOS中performSelector线程使用

2018-08-09 14:07  zhaosn  阅读(1399)  评论(0编辑  收藏  举报

Cocoa框架中 NSObject 提供了名字中包含performSelector的方法来实现多线程编程技术。

例如:

performSelectorInBackground:withObject方法;

performSelectorOnMainThread方法;

定义这些方法要遵从以下限制:

1、这些方法运行在各自的线程里,因此必须为这些Cocoa对象创建一个自动释放池;

2、这些方法不能有返回值,且要么没有参数,要么只有一个参数,格式如下:

-(void) myMethod;

-(void) myMethod:(id) myObject;

 

当方法执行完成后,OC运行时会清理并弃掉线程。方法执行结束后,并不会通知你。

如果想要在后台执行方法,如下:

[self performSelectorInBackground:@selector(doWork)  withObject:nil];

[self performSelectorInBackground:@selector(doWork)  withObject:arugmentObject];

 

////后台线程处理的方法

-(void) doWork

{

  NSAutoreleasePool *pool=[[NSAutoreleasePool  alloc] init];

  [slef  performSelectorOnMainThread:@selector(doneMainThread)  withObject:nil   waitUntilDone:NO];

  [pool  drain];

}

 

//主线程处理方法

-(void) doneMainThread

{

  //.........

}

 

//代码例子如下:

//.h文件

#import <Foundation/Foundation.h>

 @interface SelectorTester : NSObject

- (void)runSelectors;

@end

 

//.m文件

#import "SelectorTester.h"

@implementation SelectorTester

- (void)runSelectors
{
    [self performSelector:@selector(myBackgroundMehod1)];
    [self performSelector:@selector(myBackgroundMethod2:) withObject:@"Hello Selector"];
    NSLog(@"Done performing selectors");
}

- (void)myBackgroundMehod1
{
    @autoreleasepool
    {
        NSLog(@"myBackgroundMehod1");
    }
}

- (void)myBackgroundMethod2:(id)object
{
    @autoreleasepool
    {
        NSLog(@"myBackgroundMethod2 %@", object);
    }
}

@end

 

 

// main文件

#import <Foundation/Foundation.h>
#import "SelectorTester.h"

int main(int argc, const char * argv[])
{
    @autoreleasepool
    {
        SelectorTester *tester = [[SelectorTester alloc] init];
        
        [tester runSelectors];
    }
    return 0;
}