我在iphone上使用cocos2D。
我有3个场景:场景A,场景B和场景C
我只需要一个回调函数,我使用委托来成功完成此任务。
我有一个协议:
@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
他解释了如何使用块,但我无法弄清楚如何将用户的操作与块连接起来。
我知道UIViewController有一个 我发现在使用UIViewController时有一个函数:
(void)dismissViewControllerAnimated: (BOOL)flag completion: (void (^)(void))completion NS_AVAILABLE_IOS(5_0);
它支持阻止。
但我使用cocos2D,我没有找到类似的功能。
有人能给我一些建议吗?非常感谢!
答案 0 :(得分:1)
你的场景B可能有一个
@property (nonatomic, weak) id<SceneBDelegate> delegate;
而是可以将块存储在属性中:
@property(copy)void(^ dismissWithValueBlock)(BOOL); // dismissWithValueBlock是变量的名称。
然后在场景B中,按下按钮时,您可以:
-(void) clickBtn{
if(self.dismissWithBlock){
self.dismissWithBlock(YES)
}
[self removeFromParent];
}
要在其他课程中创建该块,您应该这样做:
__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'
}
答案 1 :(得分:0)
您可以按照以下方式执行此操作
//Define Block As in SceneBDelegate.h
typedef void (^onResultBlock)(NSDictionary *DictData, NSError *error);
- (void) onDismissWithValue:(onResultBlock) callbackBlock;
//Implementaion of Block As in SceneBDelegate.m
- (void) onDismissWithValue:(onResultBlock) callbackBlock
{
NSMutableDictionary *aMutDict = [[NSMutableDictionary alloc] init];
[aMutDict setValue:@"Value" forKey:@"Some Data"];
objCallback(aMutDict, nil);
}
//Call block from scene bellow
SceneBDelegate *aObjVC = [self.storyboard instantiateViewControllerWithIdentifier:@"SceneBDelegate"];
[aObjVC onDismissWithValue:^(NSDictionary *DictData, NSError *error)
{
}];
答案 2 :(得分:0)
尝试使用此代码:
@interface YourClass : NSObject {
void (^_block)(BOOL *result);
}
-(void) yourMethod:(NSString *)param1 withAnotherParam:(NSDictionary *)param2 withBlock:(void(^)(BOOL *result))block;
@implementation YourClass
-(void) yourMethod:(NSString *)param1 withAnotherParam:(NSDictionary *)param2 withBlock:(void(^)(BOOL *result))block
{
block = [block copy];
//do some stuff
block(YES);
}
然后,当您从其他班级拨打yourMethod
时,您可以执行以下操作:
@implementation OtherClass
-(void) otherMethod
{
//do other stuff
[yourClassInstance yourMethod:@"hello" withAnotherParam:@{@"hello": @"hello"} withBlock:(void(^)(BOOL *result)){
//do stuff in the block....
}];
}
我希望这会有所帮助。