programing

iOS - 지연 후 여러 인수와 함께 performSelector를 구현하는 방법은 무엇입니까?

codeshow 2023. 7. 31. 22:03
반응형

iOS - 지연 후 여러 인수와 함께 performSelector를 구현하는 방법은 무엇입니까?

저는 iOS 초보자입니다.다음과 같은 셀렉터 방법이 있습니다.

- (void) fooFirstInput:(NSString*) first secondInput:(NSString*) second
{

}

저는 이와 같은 것을 구현하려고 노력하고 있습니다.

[self performSelector:@selector(fooFirstInput:secondInput:) withObject:@"first" withObject:@"second" afterDelay:15.0];

하지만 그것은 나에게 오류를 줍니다.

Instance method -performSelector:withObject:withObject:afterDelay: not found

제가 뭘 놓쳤는지에 대한 아이디어가 있나요?

개인적으로, 저는 당신의 요구에 더 가까운 해결책이 NSInvocation을 사용하는 것이라고 생각합니다.

다음과 같은 방법으로 작업할 수 있습니다.

indexPathdataSource는 동일한 방법으로 정의된 두 인스턴스 변수입니다.

SEL aSelector = NSSelectorFromString(@"dropDownSelectedRow:withDataSource:");

if([dropDownDelegate respondsToSelector:aSelector]) {
    NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[dropDownDelegate methodSignatureForSelector:aSelector]];
    [inv setSelector:aSelector];
    [inv setTarget:dropDownDelegate];

    [inv setArgument:&(indexPath) atIndex:2]; //arguments 0 and 1 are self and _cmd respectively, automatically set by NSInvocation
    [inv setArgument:&(dataSource) atIndex:3]; //arguments 0 and 1 are self and _cmd respectively, automatically set by NSInvocation

    [inv invoke];
}

왜냐하면 그런 것은 없기 때문입니다.[NSObject performSelector:withObject:withObject:afterDelay:]방법.

전송할 데이터를 단일 목표 C 객체(예: NSRray, NSDictionary, 일부 사용자 지정 목표 C 유형)로 캡슐화한 다음 이를 통해 전달해야 합니다.[NSObject performSelector:withObject:afterDelay:]잘 알려져 있고 사랑받는 방법

예:

NSArray * arrayOfThingsIWantToPassAlong = 
    [NSArray arrayWithObjects: @"first", @"second", nil];

[self performSelector:@selector(fooFirstInput:) 
           withObject:arrayOfThingsIWantToPassAlong  
           afterDelay:15.0];

매개 변수를 하나의 개체로 패키징하고 도우미 메서드를 사용하여 Michael 및 다른 사용자가 제안한 대로 원래 메서드를 호출할 수 있습니다.

다른 옵션은 dispatch_after로, 블록을 가져와서 특정 시간에 대기열에 넣습니다.

double delayInSeconds = 15.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);

dispatch_after(popTime, dispatch_get_main_queue(), ^(void){

    [self fooFirstInput:first secondInput:second];

});

또는 이미 알아보았듯이 지연이 필요하지 않으면 사용할 수 있습니다.- performSelector:withObject:withObject:

가장 간단한 옵션은 두 인수를 모두 포함하는 단일 매개변수를 취하도록 방법을 수정하는 것입니다.NSArray또는NSDictionary(또는 단일 파라미터를 사용하여 팩을 풀고 첫 번째 메서드를 호출한 다음 지연 시 두 번째 메서드를 호출하는 두 번째 메서드를 추가합니다.)

예를 들어, 다음과 같은 것이 있을 수 있습니다.

- (void) fooOneInput:(NSDictionary*) params {
    NSString* param1 = [params objectForKey:@"firstParam"];
    NSString* param2 = [params objectForKey:@"secondParam"];
    [self fooFirstInput:param1 secondInput:param2];
}

다음과 같은 작업을 수행할 수 있습니다.

[self performSelector:@selector(fooOneInput:) 
      withObject:[NSDictionary dictionaryWithObjectsAndKeys: @"first", @"firstParam", @"second", @"secondParam", nil] 
      afterDelay:15.0];
- (void) callFooWithArray: (NSArray *) inputArray
{
    [self fooFirstInput: [inputArray objectAtIndex:0] secondInput: [inputArray objectAtIndex:1]];
}


- (void) fooFirstInput:(NSString*) first secondInput:(NSString*) second
{

}

그리고 다음과 같이 부릅니다.

[self performSelector:@selector(callFooWithArray) withObject:[NSArray arrayWithObjects:@"first", @"second", nil] afterDelay:15.0];

제공된 모든 유형의 performSelector: 메서드는 다음에서 확인할 수 있습니다.

http://developer.apple.com/library/mac/ #documentation/Cocoa/Reference/Foundation/Classes/nsobject_Class/Reference/Reference.html

여러 가지 변형이 있지만 지연뿐만 아니라 여러 개체를 사용하는 버전은 없습니다.대신 NSA ray 또는 NSDictionary로 인수를 마무리해야 합니다.

- performSelector:
- performSelector:withObject:
- performSelector:withObject:withObject:
– performSelector:withObject:afterDelay:
– performSelector:withObject:afterDelay:inModes:
– performSelectorOnMainThread:withObject:waitUntilDone:
– performSelectorOnMainThread:withObject:waitUntilDone:modes:
– performSelector:onThread:withObject:waitUntilDone:
– performSelector:onThread:withObject:waitUntilDone:modes:
– performSelectorInBackground:withObject: 

저는 NS 호출 방식을 싫어합니다. 너무 복잡합니다.단순하고 깨끗하게 유지합니다.

// Assume we have these variables
id target, SEL aSelector, id parameter1, id parameter2;

// Get the method IMP, method is a function pointer here.
id (*method)(id, SEL, id, id) = (void *)[target methodForSelector:aSelector];

// IMP is just a C function, so we can call it directly.
id returnValue = method(target, aSelector, parameter1, parameter2);

저는 그냥 스와이프를 좀 해서 원래의 방법을 불러야 했어요.제가 한 일은 프로토콜을 만들고 그것에 제 목표를 던지는 것이었습니다.또 다른 방법은 메소드를 범주에 정의하는 것이지만 경고를 억제해야 합니다(#pragma clang 진단에서 "-Wincomplete-implementation"이 무시됨).

간단하고 재사용 가능한 방법은 확장하는 것입니다.NSObject을 구현합니다.

- (void)performSelector:(SEL)aSelector withObjects:(NSArray *)arguments;

다음과 같은 것:

- (void)performSelector:(SEL)aSelector withObjects:(NSArray *)arguments
{
    NSMethodSignature *signature = [self methodSignatureForSelector: aSelector];
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature: signature];
    [invocation setSelector: aSelector];

    int index = 2; //0 and 1 reserved
    for (NSObject *argument in arguments) {
        [invocation setArgument: &argument atIndex: index];
        index ++;
    }
    [invocation invokeWithTarget: self];
}

모든 매개 변수를 속성으로 포함하는 사용자 지정 개체를 만든 다음 단일 개체를 매개 변수로 사용합니다.

단일 인수의 경우

perform(#selector(fuctionOne(_:)), with: arg1, afterDelay: 2)
@objc func fuctionOne(_ arg1: NSUserActivity) {
    // Do Something
}

다중 인수의 경우

perform(#selector(fuctionTwo(_:_:)), with: [arg1, arg2], afterDelay: 2)
@objc func fuctionTwo(_ arg1: URL, _ arg2: [UIApplication.OpenURLOptionsKey: Any] = [:]) {
    // Do Something
}

언급URL : https://stackoverflow.com/questions/8439052/ios-how-to-implement-a-performselector-with-multiple-arguments-and-with-afterd

반응형