Iphone 我可以传递函数名作为参数吗?
我想让这个类通过向它传递不同的名称来动态地在自己身上执行函数。可能吗?或者更确切地说:这怎么可能Iphone 我可以传递函数名作为参数吗?,iphone,objective-c,cocos2d-iphone,Iphone,Objective C,Cocos2d Iphone,我想让这个类通过向它传递不同的名称来动态地在自己身上执行函数。可能吗?或者更确切地说:这怎么可能 -(id)initWithMethod:(NSString*)method{ if ((self = [super init])){ [self method]; } return self; } -(void) lowHealth { CCSprite *blackScreen = [CCSprite spriteWithFile:@"bl
-(id)initWithMethod:(NSString*)method{
if ((self = [super init])){
[self method];
}
return self;
}
-(void) lowHealth {
CCSprite *blackScreen = [CCSprite spriteWithFile:@"blackscreen.png"];
blackScreen.anchorPoint = ccp(0,0);
[self addChild:blackScreen];
id fadeIn = [CCFadeIn actionWithDuration:1];
id fadeOut = [CCFadeOut actionWithDuration:1];
id fadeInAndOut = [CCRepeatForever actionWithAction:[CCSequence actions:fadeIn, fadeOut, nil]];
[blackScreen runAction:fadeInAndOut];
}
您应该使用
performSelector
并使用nsselector或fromstring
从您的NSString
获取选择器:
[self performSelector:NSSelectorFromString(method)];
而不是
[self-method]
您应该使用performSelector
并使用nsselector或fromstring
从您的NSString
获取选择器:
[self performSelector:NSSelectorFromString(method)];
而不是[self-method]代码>标准方法是使用Matteo回答中提到的方法
你也可以看看。它们在CoCoatouchAPI中变得非常常见,您可以使用它们做一些非常巧妙的事情。类的最终架构通常更容易理解
例如,此方法来自UIView
+ (void)animateWithDuration:(NSTimeInterval)duration
animations:(void (^)(void))animations
completion:(void (^)(BOOL finished))completion
获取两个块,一个用于运行实际动画的代码,另一个用于在动画完成后运行代码。您可以使用块变量或通过内联编写代码来调用:
...animations:^{
// animation code
}
completion:^(BOOL finished) {
// completion code
}
接收方法(在本例中为animateWithDuration:…)只需在某个点调用这些块,如下所示:
animations();
标准方法是使用Matteo回答中提到的方法
你也可以看看。它们在CoCoatouchAPI中变得非常常见,您可以使用它们做一些非常巧妙的事情。类的最终架构通常更容易理解
例如,此方法来自UIView
+ (void)animateWithDuration:(NSTimeInterval)duration
animations:(void (^)(void))animations
completion:(void (^)(BOOL finished))completion
获取两个块,一个用于运行实际动画的代码,另一个用于在动画完成后运行代码。您可以使用块变量或通过内联编写代码来调用:
...animations:^{
// animation code
}
completion:^(BOOL finished) {
// completion code
}
接收方法(在本例中为animateWithDuration:…)只需在某个点调用这些块,如下所示:
animations();
我认为,与其使用NSSelectorFromString(),不如将选择器传入-initWithSelector:(SEL)aSector
,还建议在调用performSelector之前调用respondsToSelector,作为断言或一般情况,以避免实例不支持该选择器时崩溃。我认为,与其使用NSSelectorFromString(),不如使用NSSelectorFromString(),选择器应在-initWithSelector:(SEL)aSector中传递,也建议在调用performSelector之前调用respondsToSelector,作为断言或一般情况,以避免实例不支持该选择器时崩溃。