YYKit源码探究(四十四) —— NSObject分类之Sending messages with variable parameters(三)

版本记录

版本号 时间
V1.0 2018.03.30

前言

iOS圈内有几个人大家基本都知道,比如说王巍、唐巧,还有YYKit框架的作者现任职于滴滴的郭曜源 - ibireme等。这里有一篇唐巧对他的专访,还有他的 GitHub - Yaoyuan博客,这里贴出来框架YYKit 框架。接下来几篇我们就一起来看一下这个框架。感兴趣的可以看上面写的几篇。
1. YYKit源码探究(一) —— 基本概览
2. YYKit源码探究(二) —— NSString分类之Hash(一)
3. YYKit源码探究(三) —— NSString分类之Encode and decode(二)
4. YYKit源码探究(四) —— NSString分类之Drawing(三)
5. YYKit源码探究(五) —— NSString分类之Regular Expression(四)
6. YYKit源码探究(六) —— NSString分类之NSNumber Compatible(五)
7. YYKit源码探究(七) —— NSString分类之Utilities(六)
8. YYKit源码探究(八) —— NSNumber分类(一)
9. YYKit源码探究(九) —— UIFont分类之架构分析和Font Traits(一)
10. YYKit源码探究(十) —— UIFont分类之Create font(二)
11. YYKit源码探究(十一) —— UIFont分类之Load and unload font(三)
12. YYKit源码探究(十二) —— UIFont分类之Dump font data(四)
13. YYKit源码探究(十三) —— UIImage分类之框架结构和Create image部分(一)
14. YYKit源码探究(十四) —— UIImage分类之Image Info(二)
15. YYKit源码探究(十五) —— UIImage分类之Modify Image(三)
16. YYKit源码探究(十六) —— UIImage分类之Image Effect(四)
17. YYKit源码探究(十七) —— UIImageView分类之架构和image部分(一)
18. YYKit源码探究(十八) —— UIImageView分类之highlight image部分(二)
19. YYKit源码探究(十九) —— UIScreen分类(一)
20. YYKit源码探究(二十) —— UIScrollView分类(一)
21. YYKit源码探究(二十一) —— UITableView分类(一)
22. YYKit源码探究(二十二) —— UITextField分类(一)
23. YYKit源码探究(二十三) —— UIView分类(一)
24. YYKit源码探究(二十四) —— UIPasteboard分类(一)
25. YYKit源码探究(二十五) —— UIGestureRecognizer分类(一)
26. YYKit源码探究(二十六) —— UIDevice分类框架及Device Information(一)
27. YYKit源码探究(二十七) —— UIDevice分类之Network Information(二)
28. YYKit源码探究(二十八) —— UIDevice分类之Disk Space(三)
29. YYKit源码探究(二十九) —— UIDevice分类之Memory Information(四)
30. YYKit源码探究(三十) —— UIDevice分类之CPU Information(五)
31. YYKit源码探究(三十一) —— UIControl分类(一)
32. YYKit源码探究(三十二) —— UIColor分类之Create a UIColor Object(一)
33. YYKit源码探究(三十三) —— UIColor分类之Get color's description(二)
34. YYKit源码探究(三十四) —— UIColor分类之Retrieving Color Information(三)
35. YYKit源码探究(三十五) —— UIButton分类之image(一)
36. YYKit源码探究(三十六) —— UIButton分类之background image(二)
37. YYKit源码探究(三十七) —— UIBezierPath分类(一)
38. YYKit源码探究(三十八) —— UIBarButtonItem分类(一)
39. YYKit源码探究(三十九) —— UIApplication分类(一)
40. YYKit源码探究(四十) —— NSTimer分类(一)
41. YYKit源码探究(四十一) —— NSParagraphStyle分类(一)
42. YYKit源码探究(四十二) —— NSObject分类之YYModel(一)
43. YYKit源码探究(四十三) —— NSObject分类之KVO(二)

回顾

上一篇主要介绍了NSObject分类KVO部分,这一篇主要看一下NSObject分类Sending messages with variable parameters部分。


框架结构

下面我们就看一下框架结构。


API - Sending messages with variable parameters

下面我们看一下API

/**
 Sends a specified message to the receiver and returns the result of the message.
 
 @param sel    A selector identifying the message to send. If the selector is
               NULL or unrecognized, an NSInvalidArgumentException is raised.
 
 @param ...    Variable parameter list. Parameters type must correspond to the
               selector's method declaration, or unexpected results may occur.
               It doesn't support union or struct which is larger than 256 bytes.
 
 @return       An object that is the result of the message.
 
 @discussion   The selector's return value will be wrap as NSNumber or NSValue
               if the selector's `return type` is not object. It always returns nil
               if the selector's `return type` is void.
 
 Sample Code:
 
     // no variable args
     [view performSelectorWithArgs:@selector(removeFromSuperView)];
     
     // variable arg is not object
     [view performSelectorWithArgs:@selector(setCenter:), CGPointMake(0, 0)];
     
     // perform and return object
     UIImage *image = [UIImage.class performSelectorWithArgs:@selector(imageWithData:scale:), data, 2.0];
     
     // perform and return wrapped number
     NSNumber *lengthValue = [@"hello" performSelectorWithArgs:@selector(length)];
     NSUInteger length = lengthValue.unsignedIntegerValue;
     
     // perform and return wrapped struct
     NSValue *frameValue = [view performSelectorWithArgs:@selector(frame)];
     CGRect frame = frameValue.CGRectValue;
 */
- (nullable id)performSelectorWithArgs:(SEL)sel, ...;

/**
 Invokes a method of the receiver on the current thread using the default mode after a delay.
 
 @warning      It can't cancelled by previous request.
 
 @param sel    A selector identifying the message to send. If the selector is
               NULL or unrecognized, an NSInvalidArgumentException is raised immediately.
 
 @param delay  The minimum time before which the message is sent. Specifying
               a delay of 0 does not necessarily cause the selector to be
               performed immediately. The selector is still queued on the
               thread's run loop and performed as soon as possible.
 
 @param ...    Variable parameter list. Parameters type must correspond to the
               selector's method declaration, or unexpected results may occur.
               It doesn't support union or struct which is larger than 256 bytes.
 
 Sample Code:
 
     // no variable args
     [view performSelectorWithArgs:@selector(removeFromSuperView) afterDelay:2.0];
     
     // variable arg is not object
     [view performSelectorWithArgs:@selector(setCenter:), afterDelay:0, CGPointMake(0, 0)];
 */
- (void)performSelectorWithArgs:(SEL)sel afterDelay:(NSTimeInterval)delay, ...;

/**
 Invokes a method of the receiver on the main thread using the default mode.
 
 @param sel    A selector identifying the message to send. If the selector is
               NULL or unrecognized, an NSInvalidArgumentException is raised.
 
 @param wait   A Boolean that specifies whether the current thread blocks until
               after the specified selector is performed on the receiver on the
               specified thread. Specify YES to block this thread; otherwise,
               specify NO to have this method return immediately.
 
 @param ...    Variable parameter list. Parameters type must correspond to the
               selector's method declaration, or unexpected results may occur.
               It doesn't support union or struct which is larger than 256 bytes.
 
 @return       While @a wait is YES, it returns object that is the result of
               the message. Otherwise return nil;
 
 @discussion   The selector's return value will be wrap as NSNumber or NSValue
               if the selector's `return type` is not object. It always returns nil
               if the selector's `return type` is void, or @a wait is YES.
 
 Sample Code:
 
     // no variable args
     [view performSelectorWithArgsOnMainThread:@selector(removeFromSuperView), waitUntilDone:NO];
     
     // variable arg is not object
     [view performSelectorWithArgsOnMainThread:@selector(setCenter:), waitUntilDone:NO, CGPointMake(0, 0)];
 */
- (nullable id)performSelectorWithArgsOnMainThread:(SEL)sel waitUntilDone:(BOOL)wait, ...;

/**
 Invokes a method of the receiver on the specified thread using the default mode.
 
 @param sel    A selector identifying the message to send. If the selector is
               NULL or unrecognized, an NSInvalidArgumentException is raised.
 
 @param thread The thread on which to execute aSelector.
 
 @param wait   A Boolean that specifies whether the current thread blocks until
               after the specified selector is performed on the receiver on the
               specified thread. Specify YES to block this thread; otherwise,
               specify NO to have this method return immediately.
 
 @param ...    Variable parameter list. Parameters type must correspond to the
               selector's method declaration, or unexpected results may occur.
               It doesn't support union or struct which is larger than 256 bytes.
 
 @return       While @a wait is YES, it returns object that is the result of
               the message. Otherwise return nil;
 
 @discussion   The selector's return value will be wrap as NSNumber or NSValue
               if the selector's `return type` is not object. It always returns nil
               if the selector's `return type` is void, or @a wait is YES.
 
 Sample Code:
 
     [view performSelectorWithArgs:@selector(removeFromSuperView) onThread:mainThread waitUntilDone:NO];
     
     [array  performSelectorWithArgs:@selector(sortUsingComparator:)
                            onThread:backgroundThread
                       waitUntilDone:NO, ^NSComparisonResult(NSNumber *num1, NSNumber *num2) {
         return [num2 compare:num2];
     }];
 */
- (nullable id)performSelectorWithArgs:(SEL)sel onThread:(NSThread *)thread waitUntilDone:(BOOL)wait, ...;

/**
 Invokes a method of the receiver on a new background thread.
 
 @param sel    A selector identifying the message to send. If the selector is
               NULL or unrecognized, an NSInvalidArgumentException is raised.
 
 @param ...    Variable parameter list. Parameters type must correspond to the
               selector's method declaration, or unexpected results may occur.
               It doesn't support union or struct which is larger than 256 bytes.
 
 @discussion   This method creates a new thread in your application, putting
               your application into multithreaded mode if it was not already.
               The method represented by sel must set up the thread environment
               just as you would for any other new thread in your program.
 
 Sample Code:
 
     [array  performSelectorWithArgsInBackground:@selector(sortUsingComparator:),
                ^NSComparisonResult(NSNumber *num1, NSNumber *num2) {
        return [num2 compare:num2];
     }];
 */
- (void)performSelectorWithArgsInBackground:(SEL)sel, ...;

/**
 Invokes a method of the receiver on the current thread after a delay.
 
 @warning     arc-performSelector-leaks
 
 @param sel   A selector that identifies the method to invoke. The method should
              not have a significant return value and should take no argument.
              If the selector is NULL or unrecognized,
              an NSInvalidArgumentException is raised after the delay.
 
 @param delay The minimum time before which the message is sent. Specifying a
              delay of 0 does not necessarily cause the selector to be performed
              immediately. The selector is still queued on the thread's run loop
              and performed as soon as possible.
 
 @discussion  This method sets up a timer to perform the aSelector message on
              the current thread's run loop. The timer is configured to run in
              the default mode (NSDefaultRunLoopMode). When the timer fires, the
              thread attempts to dequeue the message from the run loop and
              perform the selector. It succeeds if the run loop is running and
              in the default mode; otherwise, the timer waits until the run loop
              is in the default mode.
 */
- (void)performSelector:(SEL)sel afterDelay:(NSTimeInterval)delay;

下面一起详细的看一下。

1. - (nullable id)performSelectorWithArgs:(SEL)sel, ...;

该方法的作用就是向receiver发送指定的消息,并返回消息的结果。

  • sel:一个标识要发送消息的selector,如果selector是NULL或者不识别的,会抛出NSInvalidArgumentException
  • ...:变量参数列表,参数类型必须和selector方法声明的类型一致,否则可能导致不期望的错误,它不支持大于256 bytes的union或者struct。

如果selector的返回类型不是对象,selector的返回值将被包装为NSNumber or NSValue;如果selector的返回类型是void那么就会返回nil。

下面看一下示例代码。

 // no variable args
 [view performSelectorWithArgs:@selector(removeFromSuperView)];
 
 // variable arg is not object
 [view performSelectorWithArgs:@selector(setCenter:), CGPointMake(0, 0)];
 
 // perform and return object
 UIImage *image = [UIImage.class performSelectorWithArgs:@selector(imageWithData:scale:), data, 2.0];
 
 // perform and return wrapped number
 NSNumber *lengthValue = [@"hello" performSelectorWithArgs:@selector(length)];
 NSUInteger length = lengthValue.unsignedIntegerValue;
 
 // perform and return wrapped struct
 NSValue *frameValue = [view performSelectorWithArgs:@selector(frame)];
 CGRect frame = frameValue.CGRectValue;

方法实现

- (id)performSelectorWithArgs:(SEL)sel, ...{
    INIT_INV(sel, nil);
    [inv invoke];
    return [NSObject getReturnFromInv:inv withSig:sig];
}

+ (id)getReturnFromInv:(NSInvocation *)inv withSig:(NSMethodSignature *)sig {
    NSUInteger length = [sig methodReturnLength];
    if (length == 0) return nil;
    
    char *type = (char *)[sig methodReturnType];
    while (*type == 'r' || // const
           *type == 'n' || // in
           *type == 'N' || // inout
           *type == 'o' || // out
           *type == 'O' || // bycopy
           *type == 'R' || // byref
           *type == 'V') { // oneway
        type++; // cutoff useless prefix
    }
    
#define return_with_number(_type_) \
do { \
_type_ ret; \
[inv getReturnValue:&ret]; \
return @(ret); \
} while (0)
    
    switch (*type) {
        case 'v': return nil; // void
        case 'B': return_with_number(bool);
        case 'c': return_with_number(char);
        case 'C': return_with_number(unsigned char);
        case 's': return_with_number(short);
        case 'S': return_with_number(unsigned short);
        case 'i': return_with_number(int);
        case 'I': return_with_number(unsigned int);
        case 'l': return_with_number(int);
        case 'L': return_with_number(unsigned int);
        case 'q': return_with_number(long long);
        case 'Q': return_with_number(unsigned long long);
        case 'f': return_with_number(float);
        case 'd': return_with_number(double);
        case 'D': { // long double
            long double ret;
            [inv getReturnValue:&ret];
            return [NSNumber numberWithDouble:ret];
        };
            
        case '@': { // id
            id ret = nil;
            [inv getReturnValue:&ret];
            return ret;
        };
            
        case '#': { // Class
            Class ret = nil;
            [inv getReturnValue:&ret];
            return ret;
        };
            
        default: { // struct / union / SEL / void* / unknown
            const char *objCType = [sig methodReturnType];
            char *buf = calloc(1, length);
            if (!buf) return nil;
            [inv getReturnValue:buf];
            NSValue *value = [NSValue valueWithBytes:buf objCType:objCType];
            free(buf);
            return value;
        };
    }
#undef return_with_number
}

2. - (void)performSelectorWithArgs:(SEL)sel afterDelay:(NSTimeInterval)delay, ...;

延迟一定时间后,使用默认模式在当前线程上调用receiver的方法。

注意:不能通过先前的request取消。

  • sel:一个指定要发送消息的selector,如果selector是NULL或者无法识别,那么就会引起错误NSInvalidArgumentException
  • delay:在消息被发出前的最小时间,指定为0并不能保证立即执行,selector仍然会在线程run loop中进行排队,并会尽快执行。
  • ...:变量参数列表,参数类型必须和selector方法声明类型一致,否则会引起无法预期的错误,不支持大于256 bytes的union或者struct。

示例代码

 // no variable args
 [view performSelectorWithArgs:@selector(removeFromSuperView) afterDelay:2.0];
 
 // variable arg is not object
 [view performSelectorWithArgs:@selector(setCenter:), afterDelay:0, CGPointMake(0, 0)];

方法实现

- (void)performSelectorWithArgs:(SEL)sel afterDelay:(NSTimeInterval)delay, ...{
    INIT_INV(delay, );
    [inv retainArguments];
    [inv performSelector:@selector(invoke) withObject:nil afterDelay:delay];
}

3. - (nullable id)performSelectorWithArgsOnMainThread:(SEL)sel waitUntilDone:(BOOL)wait, ...;

该方法的作用就是使用default mode在主线程中调用receiver的方法。

  • wait:一个BOOL值,指定当前线程是否阻塞直到在指定的线程执行完指定的selector,指定为YES阻塞这个线程,否则NO表示立即返回。

如果selector的返回类型不是对象,那么返回结果被包装为NSNumber or NSValue,如果selector的返回类型是void,那么wait就是YES。

示例代码

 // no variable args
 [view performSelectorWithArgsOnMainThread:@selector(removeFromSuperView), waitUntilDone:NO];
 
 // variable arg is not object
 [view performSelectorWithArgsOnMainThread:@selector(setCenter:), waitUntilDone:NO, CGPointMake(0, 0)];

方法实现

- (id)performSelectorWithArgsOnMainThread:(SEL)sel waitUntilDone:(BOOL)wait, ...{
    INIT_INV(wait, nil);
    if (!wait) [inv retainArguments];
    [inv performSelectorOnMainThread:@selector(invoke) withObject:nil waitUntilDone:wait];
    return wait ? [NSObject getReturnFromInv:inv withSig:sig] : nil;
}

4. - (nullable id)performSelectorWithArgs:(SEL)sel onThread:(NSThread *)thread waitUntilDone:(BOOL)wait, ...;

该方法的作用就是使用default mode在指定线程执行receiver方法。这个方法和上面那个方法的区别就是这个可以指定线程,上面那个方法是主线程。

示例代码

 [view performSelectorWithArgs:@selector(removeFromSuperView) onThread:mainThread waitUntilDone:NO];
 
 [array  performSelectorWithArgs:@selector(sortUsingComparator:)
                        onThread:backgroundThread
                   waitUntilDone:NO, ^NSComparisonResult(NSNumber *num1, NSNumber *num2) {
     return [num2 compare:num2];
 }];

方法实现

- (id)performSelectorWithArgs:(SEL)sel onThread:(NSThread *)thr waitUntilDone:(BOOL)wait, ...{
    INIT_INV(wait, nil);
    if (!wait) [inv retainArguments];
    [inv performSelector:@selector(invoke) onThread:thr withObject:nil waitUntilDone:wait];
    return wait ? [NSObject getReturnFromInv:inv withSig:sig] : nil;
}

5. - (void)performSelectorWithArgsInBackground:(SEL)sel, ...;

该方法的作用就是在后台线程中执行指定receiver的方法。

这个方法在你的应用程序中创建一个新的线程,如果你的应用程序还没有进入多线程模式。 由sel表示的方法必须像在程序中的其他任何新线程一样设置线程环境。

示例代码

 [array  performSelectorWithArgsInBackground:@selector(sortUsingComparator:),
            ^NSComparisonResult(NSNumber *num1, NSNumber *num2) {
    return [num2 compare:num2];
 }];

方法实现

- (void)performSelectorWithArgsInBackground:(SEL)sel, ...{
    INIT_INV(sel, );
    [inv retainArguments];
    [inv performSelectorInBackground:@selector(invoke) withObject:nil];
}

6. - (void)performSelector:(SEL)sel afterDelay:(NSTimeInterval)delay;

该方法的作用就是在当前线程中延迟一定时间指定receiver的方法。

注意:arc-performSelector-leaks

此方法设置一个计时器以在当前线程的运行循环中执行aSelector消息。 定时器配置为以默认模式运行(NSDefaultRunLoopMode)。 当定时器触发时,线程将尝试从运行循环中出列消息并执行selector。 如果运行循环运行并处于默认模式,则成功; 否则,定时器会一直等到运行循环处于默认模式。

方法实现

- (void)performSelector:(SEL)sel afterDelay:(NSTimeInterval)delay {
    [self performSelector:sel withObject:nil afterDelay:delay];
}

后记

本篇主要讲述了NSObject分类的Sending messages with variable parameters,感兴趣的给个赞或者关注,谢谢~~~

推荐阅读更多精彩内容