gpt4 book ai didi

iOS:如何使用 block 完成此委托(delegate)代码

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:17:42 25 4
gpt4 key购买 nike

我在 iphone 上使用 cocos2D。

我有3个场景:场景A、场景B、场景C

  1. 在场景C中,点击打开场景A,但是场景A还没有打开;
  2. 先打开场景B,场景B有很多按钮
  3. 用户在场景B上点击了一个按钮,然后场景B消失并返回一个值v给场景C;
  4. 场景C根据值v决定是否开启场景A;

我只需要一个回调函数,我使用委托(delegate)来成功完成。

我有一个协议(protocol):

@protocol SceneBDelegate <NSObject>
@required
- (void)dismissWithValue:(BOOL)value;
@end

在场景B中,点击按钮时:

-(void) clickBtn{

if([self.delegate respondsToSelector:@selector(dismissWithValue:)]){
[self.delegate dismissWithValue: YES];
}

[self removeFromParent];
}

在场景C中,

-(void) dismissWithValue:(BOOL)value{
if(value){
// do something;
}
}

这些代码运行良好,但我想知道如何使用 block 来完成此操作?

我读过 Jens Ayton 的帖子是这个问题, how-to-perform-callbacks-in-objective-c

他解释了如何使用 block ,但我不知道如何将用户的操作与 block 联系起来。

我知道 UIViewController 有一个我在使用 UIViewController 时发现有一个功能:

(void)dismissViewControllerAnimated: (BOOL)flag completion: (void (^)(void))completion NS_AVAILABLE_IOS(5_0);

它支持 block 。

但是我用的是cocos2D,没有找到类似的功能。

谁能给我一些建议?非常感谢!

最佳答案

你的场景B可能有一个

@property (nonatomic, weak) id<SceneBDelegate> delegate;

相反,您可以在属性中存储一个 block :

@property (copy)void (^dismissWithValueBlock)(BOOL);//dismissWithValueBlock 是变量的名称。

然后在你的场景 B 中,当按下按钮时你会:

-(void) clickBtn{

if(self.dismissWithBlock){
self.dismissWithBlock(YES)
}

[self removeFromParent];
}

要在你的其他类中创建 block ,你应该这样做:

__weak typeof (self) weakSelf = self;

sceneB.dismissWithBlock = ^(BOOL value)
{
typeof (self) strongSelf = self;
// .... now your code you want to execute when this block is called..
// make sure not to call self.XXX anywhere in here. You should use the strongSelf.XXX insteadd! This is for memory management purposes. You can read up on it by googling 'strongSelf in blocks ios'
}

关于iOS:如何使用 block 完成此委托(delegate)代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25460386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com