2011-12-26 179 views
1

我想让这个类通过传递不同的名字来动态地执行它自己的函数。那可能吗 ?或者说:它怎么可能?我可以传递函数名称作为参数吗?

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

回答

7

您应该使用performSelector和使用NSSelectorFromStringNSString得到选择:中

[self performSelector:NSSelectorFromString(method)]; 

代替[self method];

+4

你可以用块变量或通过编写代码内嵌调用此我认为,不应该使用NSSelectorFromString(),而应该在'-initWithSelector中传递一个选择器:(SEL)aSector' – vikingosegundo 2011-12-26 23:18:38

+0

在调用performSelector之前调用respondsToSelector也是可取的,既可以作为断言,也可以在一般情况下避免崩溃,如果实例不不支持那个选择器。 – LearnCocos2D 2011-12-29 20:37:17

1

在利玛窦的答案中提到的标准方法是使用Selectors

你也可以看看Objective-C Blocks。它们在CocoaTouch API中变得非常常见,你可以用它们做一些非常光滑的事情。由此产生的班级结构往往更易于理解IMO。

例如从UIView的

+ (void)animateWithDuration:(NSTimeInterval)duration 
       animations:(void (^)(void))animations 
       completion:(void (^)(BOOL finished))completion 

此方法需要两个块,一个是运行的实际动画的代码,以及一个用于该代码的动画完成后。

...animations:^{ 
     // animation code 
    } 
    completion:^(BOOL finished) { 
     // completion code 
    } 

的接收方法(在这种情况下animateWithDuration:...)将只调用这些块在某些时候,像这样:

animations(); 
相关问题