从块内调用?

我刚刚遇到了块,我认为他们就是我正在寻找,除了一件事情:是否可以从一个块内调用一个方法[self methodName]?

这就是我想要做的:

-(void)someFunction{ Fader* fader = [[Fader alloc]init]; void (^tempFunction)(void) = ^ { [self changeWindow:game]; //changeWindow function is located in superclass }; [fader setFunction:tempFunction]; } 

我一直在寻找几天,我找不到任何证据表明这是可能的。

这是可能的,还是我试图使用块他们不是为了什么?

我使用块的原因是我创build了一个Fader类,我想存储一个块,当它完成淡出时执行。

谢谢

编辑:好的,我在build议中添加了,但我仍然得到一个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]; } 

也许我不允许推子function…?

是的,你可以做到这一点。

但是,请注意,该块将保留self 。 如果您最终将这个块存储在ivar中,您可以轻松创build一个保留周期,这意味着两者都不会被释放。

为了解决这个问题,你可以这样做:

 - (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]?

是的,为什么不。 如果你的tempFunction是一个实例方法,你可以这样做。 被调用的方法应该是唯一的限制。

我想知道你是否[fader setFunction:tempFunction]; 然后是同步的或asynchronous的。 如果你不保留它,它会popup。

 -(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.