我可以传递一个函数名作为参数吗?

the*_*tic 1 iphone objective-c cocos2d-iphone

我想让这个类通过向它传递不同的名称来动态地执行函数.那可能吗 ?或者更确切地说:它怎么可能?

-(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];
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*ani 7

您应该使用performSelector并从您的NSString使用中获取选择器NSSelectorFromString:

[self performSelector:NSSelectorFromString(method)];
Run Code Online (Sandbox Code Playgroud)

代替 [self method];

  • 我认为,不是使用NSSelectorFromString(),而是应该在`-initWithSelector:(SEL)aSector中传递一个选择器. (4认同)