从块内部调用[self methodName]? [英] Calling [self methodName] from inside a block?

查看:81
本文介绍了从块内部调用[self methodName]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚遇到块,我想它们就是我想要的东西,除了一件事:是否可以从块内调用方法[self methodName]?

I've just run into blocks and I think they are just what I'm looking for, except for one thing: is it possible to call a method [self methodName] from within a block?

这就是我想要做的:

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

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

    [fader setFunction:tempFunction];
}

我已经搜寻了几天,但找不到任何证据证明这是可能的.

I've been searching for a couple of days and I can't find any evidence that this is possible.

这是完全可能的吗,还是我在尝试将块用于不是他们想要的东西?

Is this at all possible, or am I trying to use blocks for something they aren't meant for?

我使用块的原因是我创建了一个Fader类,并且我想存储一个块供其完成淡出时执行.

The reason I'm using blocks is that I've created a Fader class, and I want to store a block for it to execute when it finishes fading out.

谢谢

好的,我添加了建议,但仍然出现EXC_BAD_ACCESS错误...

Okay, I added in the suggestion, but I'm still getting an EXC_BAD_ACCESS error...

-(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];
}

也许不允许我给 fader 函数...?

Maybe I'm not allowed to give fader the function...?

推荐答案

是的,您可以这样做.

但是,请注意,该块将保留self.如果最终将此块存储在一个ivar中,则可以轻松创建一个保留周期,这意味着它们都不会被释放.

Note, however, that the block will retain self. If you end up storing this block in an ivar, you could easily create a retain cycle, which means neither would ever get deallocated.

要解决此问题,您可以执行以下操作:

To get around this, you can do:

- (void) someMethodWithAParameter:(id)aParameter {

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

  [self doSomethingWithBlock:tempFunction];

}

__block关键字(除其他事项外)表示将不会保留所引用的对象.

The __block keyword means (among other things) that the referenced object will not be retained.

这篇关于从块内部调用[self methodName]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆