ProgramingTip

사용으로 사용할 블록을 취하는 메소드 구현

bestdevel 2020. 11. 5. 08:23
반응형

사용으로 사용할 블록을 취하는 메소드 구현


다음과 방법을 제안하고 싶습니다.

+(void)myMethodWithView:(UIView *)exampleView completion:(void (^)(BOOL finished))completion;

기본적으로 다음과 같은 Apple의 클래스 메소드 중 하나에서 장비 구문을 제거했습니다 UIView.

+ (void)animateWithDuration:(NSTimeInterval)duration delay:(NSTimeInterval)delay options:(UIViewAnimationOptions)options animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion;

그리고 다음과 같이 사용되기를 기대합니다.

[myFoo myMethodWithView:self.view completion:^(BOOL finished){
                     NSLog(@"call back success");
                 }];

내 질문은 어떻게 구현할 수 있습니까? 누군가 나에게 훌륭한 문서를 알려줄 수 있고 매우 기본적인 예제를 많이 주시면 감사합니다 (또는 Stack Overflow에 대한 대답-찾을 수 없음). 나는 그것이 올바른 접근 방식인지 결정하기 위해 델리게이트에 대해 충분히 알지 못합니다!

구현 파일에있을 것으로 예상되는 것으로 추측됩니다.

+ (void)myMethod:(UIView *)exampleView completion:(void (^)(BOOL finished))completion {
    // do stuff

    if (completion) {
        // what sort of syntax goes here? If I've constructed this correctly!
    }

}

일반 함수처럼 블록을 호출 할 수 있습니다.

BOOL finished = ...;
if (completion) {
    completion(finished);
}

따라서 예제를 사용하여 완전한 블록 함수를 구현하는 것은 다음과 가능합니다.

+ (void)myMethod:(UIView *)exampleView completion:(void (^)(BOOL finished))completion {
    if (completion) {
        completion(finished);
    }
}

무슨 일이 일어나고 있는지 이해하기 위해 Blocks읽는 것이 좋습니다 .


특별히 문서를 찾고, 블록을 사용하여 사용자 지정 메소드를 만드는 경우 다음 링크가 이에 대한 거의 모든 것을 설명하는 링크입니다. :)

http://developer.apple.com/library/ios/documentation/cocoa/Conceptual/Blocks/Articles/bxUsing.html

나는 최근에 꽤 같은 질문에 대답했습니다. 명세서 : typedef를 사용하지 않고리스트 변수를 검증 합니다.

참고 URL : https://stackoverflow.com/questions/7180552/implementing-a-method-taking-a-block-to-use-as-callback

반응형