NSInvocation 의 첫 만남

2217 단어

전언


최근 Effective Objective-C 2.0이라는 책을 읽다가 메시지 전달 메커니즘이라는 부분을 소개하던 중 NSInvocation 같은 종류를 만났다.애플은 NSInvocation을 대상으로 Objective-C 메시지를 전달했다고 공식 설명했다.
An Objective-C message rendered as an object. NSInvocation objects are used to store and forward messages between objects and between applications, primarily by NSTimer objects and the distributed objects system. An NSInvocation object contains all the elements of an Objective-C message: a target, a selector, arguments, and the return value. Each of these elements can be set directly, and the return value is set automatically when the NSInvocation object is dispatched.
하나의 NSInvocation 대상은 Objective-C 메시지의 모든 요소를 포함합니다: target, selector,argument,return value.각 요소를 직접 설정하고 NSInvocation에서 객체를 할당할 때 반환 값을 자동으로 설정할 수 있습니다.
이른바 방법 서명, 즉 방법에 대응하는 반환값 유형과 파라미터 유형이다.NSInvocation이 호출되면 실행 시 대상 대상을 통해 대응하는 방법을 찾아 유일성을 확보합니다. [receiver message]로 설명할 수 있습니다.실제 개발 과정에서 NSInvocation을 직접 만드는 경우는 드물며 이런 일은 보통 시스템에 맡긴다.예를 들어 뱅의 JSPatch에서arm64 방법 교체의 실현은runtime 메시지를 마지막 단계의 NSInvocation으로 전달하는 것이다.

NSInvocation의 일반적인 사용 방법


다음 문자열 결합을 예로 들면, 이 방법의 호출을 NSInvocation 메시지로 변환해 보겠습니다.
NSString *string = @"Hello";
NSString *addString = [string stringByAppendingString:@" World!"];

NSInvocation으로 변환한 후:
NSString *string = @"Hello";
void* addString;
NSString* stringToAppend = @" World!";
//invocationWithMethodSignature:  。
NSMethodSignature *signature = [string methodSignatureForSelector:@selector(stringByAppendingString:)];
NSInvocation* invocation = [NSInvocation invocationWithMethodSignature:signature];
// target
invocation.target = string;
invocation.selector = @selector(stringByAppendingString:);
// World! ,index 2  0、1 target selector 
[invocation setArgument:&stringToAppend atIndex:2];
// , 
[invocation invoke];
//   addString
if (signature.methodReturnLength > 0) {
    [invocation getReturnValue:&addString];
    NSString *str = (__bridge NSString *)addString;
    NSLog(@"%@",str);
}

일반적으로 NSInvocation을 통해 메시지를 전송하여 정의되지 않은 방법을 실현하고runtime를 통해 메시지의 동적 발송을 실현한다.
그 다음에 NSInvocation에 대한 연구를 덧붙이겠습니다!

좋은 웹페이지 즐겨찾기