iOS performSelector方法總結(jié)

perfromSelector 的非延遲方法

- (id)performSelector:(SEL)aSelector;
- (id)performSelector:(SEL)aSelector withObject:(id)object;
- (id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:(id)object2;

底層實現(xiàn) 源碼地址

- (id)performSelector:(SEL)sel {
    if (!sel) [self doesNotRecognizeSelector:sel];
    return ((id(*)(id, SEL))objc_msgSend)(self, sel);
}

- (id)performSelector:(SEL)sel withObject:(id)obj {
    if (!sel) [self doesNotRecognizeSelector:sel];
    return ((id(*)(id, SEL, id))objc_msgSend)(self, sel, obj);
}

- (id)performSelector:(SEL)sel withObject:(id)obj1 withObject:(id)obj2 {
    if (!sel) [self doesNotRecognizeSelector:sel];
    return ((id(*)(id, SEL, id, id))objc_msgSend)(self, sel, obj1, obj2);
}

performSelector是運行時系統(tǒng)負責去找方法,在編譯時不會對調(diào)用的方法做檢查,只有在運行的時候才會檢查,如果方法存在就調(diào)用,如果放不存在就不會調(diào)用。當然也可以通過使用 - (BOOL)respondsToSelector:(SEL)aSelector;方法去判斷對象是否實現(xiàn)了要調(diào)用的方法。

這三個方法調(diào)用都是直接執(zhí)行,相當于直接通過對象調(diào)用方法, [self performSelector:@selector(test)];與[self test]; 執(zhí)行的結(jié)果是一致的,通過這些方法去執(zhí)行是不需要子線程去啟動Runloop的。方法內(nèi)運行的線程就是調(diào)用performSelector所在的線程

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"當前線程:%@",[NSThread currentThread]);
    [self performSelector:@selector(test1)];
    [self performSelector:@selector(test2:) withObject:@"小明"];
    [self performSelector:@selector(test3:andAge:) withObject:@"小明" withObject:@"10"];
    NSLog(@"****************************************");
    dispatch_queue_t queue = dispatch_queue_create("新的并發(fā)隊列", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue, ^{
        NSLog(@"當前線程:%@",[NSThread currentThread]);
        [self performSelector:@selector(test1)];
        [self performSelector:@selector(test2:) withObject:@"小明"];
        [self performSelector:@selector(test3:andAge:) withObject:@"小明" withObject:@"10"];
    });
}

-(void)test1{
    NSLog(@"執(zhí)行了test1 當前線程:%@",[NSThread currentThread]);
}

-(void)test2:(NSString *)name{
    NSLog(@"執(zhí)行了test2 name:%@ 當前線程:%@",name,[NSThread currentThread]);
}

-(void)test3:(NSString *)name andAge:(NSString *) age{
    NSLog(@"執(zhí)行了test3 name:%@ age:%@ 當前線程:%@",name,age,[NSThread currentThread]);
}
/*輸出
 當前線程:<NSThread: 0x600000624a80>{number = 1, name = main}
 執(zhí)行了test1 當前線程:<NSThread: 0x600000624a80>{number = 1, name = main}
 執(zhí)行了test2 name:小明 當前線程:<NSThread: 0x600000624a80>{number = 1, name = main}
 執(zhí)行了test3 name:小明 age:10 當前線程:<NSThread: 0x600000624a80>{number = 1, name = main}
 ****************************************
 當前線程:<NSThread: 0x60000066d380>{number = 6, name = (null)}
 執(zhí)行了test1 當前線程:<NSThread: 0x60000066d380>{number = 6, name = (null)}
 執(zhí)行了test2 name:小明 當前線程:<NSThread: 0x60000066d380>{number = 6, name = (null)}
 執(zhí)行了test3 name:小明 age:10 當前線程:<NSThread: 0x60000066d380>{number = 6, name = (null)}
  */

上面的方法,最多可以支持傳遞2個參數(shù),如果要傳遞2個以上,上面的方法就不能使用了。

  1. 方法一 objc_msgSend
((void (*) (id, SEL, NSString *, NSString *, NSString *)) objc_msgSend) (self, @selector(test4:andAge:andSex:), @"小明", @"10", @"男");

-(void)test4:(NSString *)name andAge:(NSString *) age andSex:(NSString *)sex{
    NSLog(@"執(zhí)行了test4 name:%@ age:%@ sex:%@ 當前線程:%@",name,age,sex,[NSThread currentThread]);
}

/*輸出
執(zhí)行了test4 name:小明 age:10 sex:男 當前線程:<NSThread: 0x600000a68580>{number = 1, name = main}
*/
  1. 方法二 NSInvocation

      //1、方法簽名
      NSMethodSignature *signature = [[self class]instanceMethodSignatureForSelector:@selector(test4:andAge:andSex:)];
        //包裝方法
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
        //方法調(diào)用者
         invocation.target = self;
         //要調(diào)用的方法和方法簽名中的方法一樣
        invocation.selector = @selector(test4:andAge:andSex:);
        NSString *name = @"小明";
        NSString *age = @"10";
        NSString *sex = @"男";
        //設(shè)置傳遞的參數(shù) 0 代表target 1代表 selector 所以從2開始
        [invocation setArgument:&name atIndex:2];
        [invocation setArgument:&age atIndex:3];
        [invocation setArgument:&sex atIndex:4];
        //執(zhí)行方法
        [invocation invoke];
        //獲取返回值
        NSString *returnValue = @"";
        [invocation getReturnValue:&returnValue];
        NSLog(@"返回值:%@",returnValue);
        
        
    -(NSString *)test4:(NSString *)name andAge:(NSString *) age andSex:(NSString *)sex{
        NSLog(@"執(zhí)行了test4 name:%@ age:%@ sex:%@ 當前線程:%@",name,age,sex,[NSThread currentThread]);
        return @"這是返回值";
    }
    
    /*
     執(zhí)行了test4 name:小明 age:10 sex:男 當前線程:<NSThread: 0x600000f9c980>{number = 1, name = main}
      返回值:這是返回值
    */
    

performSelector 的延遲執(zhí)行方法

- (void)performSelector:(SEL)aSelector withObject:(nullable id)anArgument afterDelay:(NSTimeInterval)delay inModes:(NSArray<NSRunLoopMode> *)modes;

- (void)performSelector:(SEL)aSelector withObject:(nullable id)anArgument afterDelay:(NSTimeInterval)delay;

在蘋果文檔中的介紹:

這個方法是設(shè)置了一個timer,在當前線程的runloop上執(zhí)行aSelector消息,這個計時器的默認模式是NSDefaultRunLoopMode。當計時器觸發(fā)時,會嘗試從runloop中取出消息行,如果runloop運行的模式是NSDefaultRunLoopMode,那么就會執(zhí)行它,如果當前runloop是其他模式,則會等待runloop處于NSDefaultRunLoopMode在運行。

如果希望在運行循環(huán)處于NSDefaultRunLoopMode以外的其他模式時使消息出隊,請改用performSelector:withObject:afterDelay:inModes:方法。如果不確定當前線程是否為主線程,則可以使用performSelectorOnMainThread:withObject:waitUntilDone:或performSelectorOnMainThread:withObject:waitUntilDone:modes:方法來確保選擇器在主線程上執(zhí)行。要取消排隊的消息,請使用cancelPreviousPerformRequestsWithTarget:或cancelPreviousPerformRequestsWithTarget:selector:object:方法。

特別注意事項
此方法向其當前上下文的runloop進行注冊,并依賴于runloop才能正確執(zhí)行。一種常見情況是,當在 dispatch queue上調(diào)用這個方法,但是runloop并沒有啟動,這個方法是不會運行的。如果想使用這個延遲功能在dispatch queue上,則應使用dispatch_after和相關(guān)方法來獲得所需的行為。

Runloop源碼地址

  1. 在主線程中調(diào)用
-(void)test1:(NSString *)name{
    NSLog(@"執(zhí)行了test1 name:%@ 當前線程:%@",name,[NSThread currentThread]);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //在主線程中,它的runloop是默認開啟的,所有下面的方法是可以直接執(zhí)行
    [self performSelector:@selector(test1:) withObject:@"小明" afterDelay:2];
}


//輸出
//執(zhí)行了test1 name:小明 當前線程:<NSThread: 0x6000012a8b00>{number = 1, name = main}

  1. 在隊列中,不調(diào)用[[NSRunLoop currentRunLoop] run];
- (void)viewDidLoad {
    [super viewDidLoad];
    dispatch_queue_t queue = dispatch_queue_create("并發(fā)隊列", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue, ^{
        //這個方法是不會執(zhí)行的,因為此時的這個線程的runloop默認是沒有開啟的
        [self performSelector:@selector(test1:) withObject:@"小紅" afterDelay:2];
    });
}
  1. 在隊列中,在調(diào)用performSelector之前調(diào)用[[NSRunLoop currentRunLoop] run];
- (void)viewDidLoad {
    [super viewDidLoad];
    dispatch_queue_t queue = dispatch_queue_create("并發(fā)隊列", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue, ^{
        [[NSRunLoop currentRunLoop] run];
        //這個方法是不會執(zhí)行的,調(diào)用run方法只是嘗試開啟當前線程中的runloop,但是如果該線程中并沒有任何事件(source、timer、observer)的話,runloop并不會開啟。
        [self performSelector:@selector(test1:) withObject:@"小紅" afterDelay:1];
    });
}
  1. 在隊列中,在調(diào)用performSelector之后調(diào)用[[NSRunLoop currentRunLoop] run];
-(void)viewDidLoad {
    [super viewDidLoad];
    dispatch_queue_t queue = dispatch_queue_create("并發(fā)隊列", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue, ^{
        //成功調(diào)用函數(shù)
        [self performSelector:@selector(test1:) withObject:@"小紅" afterDelay:1];
        [[NSRunLoop currentRunLoop] run];
    });
}
//輸出
//執(zhí)行了test1 name:小紅 當前線程:<NSThread: 0x6000015b0a00>{number = 7, name = (null)}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。