developer tip

블록 내부에서 [self methodName] 호출?

optionbox 2020. 10. 26. 07:54
반응형

블록 내부에서 [self methodName] 호출?


방금 블록에 부딪 혔는데 한 가지를 제외하고는 내가 찾던 것 뿐이라고 생각합니다. 블록 내에서 [self methodName] 메서드를 호출 할 수 있습니까?

이것이 내가하려는 것입니다.

-(void)someFunction{
    Fader* fader = [[Fader alloc]init];

    void (^tempFunction)(void) = ^ {
        [self changeWindow:game]; 
        //changeWindow function is located in superclass
    };

    [fader setFunction:tempFunction];
}

며칠 동안 수색을 해왔지만 이것이 가능하다는 증거를 찾을 수 없습니다.

이것이 가능합니까, 아니면 의도하지 않은 것을 위해 블록을 사용하려고합니까?

블록을 사용하는 이유는 Fader 클래스를 만들었고 페이드 아웃이 끝났을 때 실행할 블록을 저장하고 싶기 때문입니다.

감사합니다

편집 : 좋아, 제안에 추가했지만 여전히 EXC_BAD_ACCESS 오류가 발생합니다 ...

-(void)someFunction{
    Fader* fader = [[Fader alloc]init];

    __block MyScreen* me = self;

    void (^tempFunction)(void) = ^ {
        [me changeWindow:game]; 
        //changeWindow function is located in superclass
    };

    [fader setFunction:tempFunction];
    [fader release];
}

페이더 에 기능 을 부여 할 수없는 것 같은데 ...?


예, 할 수 있습니다.

그러나 블록은 self. 이 블록을 ivar에 저장하면 유지주기를 쉽게 생성 할 수 있습니다. 즉, 둘 다 할당 해제되지 않습니다.

이 문제를 해결하려면 다음을 수행 할 수 있습니다.

- (void) someMethodWithAParameter:(id)aParameter {

  __block MySelfType *blocksafeSelf = self;
  void (^tempFunction)(void) = ^ {
      [blocksafeSelf changeWindow:game];
  };

  [self doSomethingWithBlock:tempFunction];

}

__block참조 된 개체가 유지되지 않습니다 (다른 것들 사이) 키워드를 의미합니다.


허용되는 답변은 구식 입니다. __block이 경우 사용 하면 오류가 발생할 수 있습니다!

이 문제를 방지하려면 다음 과 같이에 대한 약한 참조를 캡처하는 것이 좋습니다 self.

- (void)configureBlock {
    XYZBlockKeeper * __weak weakSelf = self;
    self.block = ^{
        [weakSelf doSomething];   // capture the weak reference
                                  // to avoid the reference cycle
    }
}

자세한 내용은 Apple 문서- 자기 캡처시 강력한 참조주기 방지 를 참조하십시오.


__block CURRENTViewController *blocksafeSelf = self;

[homeHelper setRestAsCheckIn:strRestId :^(NSObject *temp) {
    [blocksafeSelf YOURMETHOD:params];
}];

블록 내에서 [self methodName] 메서드를 호출 할 수 있습니까?

Yes, why not. If your tempFunction is an instance method, you can do it. The called method should be accessible is the only restriction.


I wonder whether you [fader setFunction:tempFunction]; then is synchronous or asynchronous. blocks push onto stack.so in MRR,if you don't retain it,it will pop off.

-(void)someFunction{
    Fader* fader = [[Fader alloc]init];

    void (^tempFunction)(void) = ^ {
        [self changeWindow:game]; 
        //changeWindow function is located in superclass
    };

    [fader setFunction:tempFunction];
    //if the tempFunction execute there will be right.
}//there the tempFunction pop off
 //....some thing go on
 //execute the tempFunction will go wrong.

참고URL : https://stackoverflow.com/questions/5023566/calling-self-methodname-from-inside-a-block

반응형