Search code examples
iphoneobjective-cios5xcode4.2kobold2d

How to passing class argument to selector in objective C?


I want to set the class tile value by click on the button

  • if click onPlus it will have a string value = @"+"
  • if click onMinus it will have a string value = @"-"

here are the code

//Class Tile

@interface Tile : TouchableNode {
     NSString *val;
}

-(void) setVal:(NSString *)v
{
    val = v;
}

-(NSString *) getVal
{
    return val;
}

And the in another class

I have a code like this

for(Tile *tile in player)
{
    if (tile.getVal == @"P") {
        if (pauseStatus == 0) {
            pauseStatus = 1;

            [[CCDirector sharedDirector] pause];
            CGSize size = [[CCDirector sharedDirector] winSize];
            pauseLayer=[[CCLayer alloc] init];
            pauseLayer.anchorPoint=ccp(0,0);
            pauseLayer = [CCLayerColor layerWithColor: ccc4(0, 0, 255, 125) width: 300 height: 150];
            pauseLayer.position = ccp(size.width/2, size.height/2);       
            pauseLayer.isRelativeAnchorPoint = YES;
            [self addChild: pauseLayer z:8];

            //Here are 2 two button that when user click it will have @"+" value or @"-"
            plusBtn = [CCMenuItemImage itemFromNormalImage:@"plus.png" selectedImage:@"plus.png"     target:self selector:@selector(onPlus:)];
            minusBTn = [CCMenuItemImage itemFromNormalImage:@"minus.png" selectedImage:@"minus.png"      target:self selector:@selector(onMinus:)];

            pauseMenu = [CCMenu menuWithItems:plusBtn, minusBTn, nil];
            [pauseMenu alignItemsHorizontally];
            [self addChild:pauseMenu z:10];
        }
    }
}

and I have onPlus & onMinus method that I want to send object tile to that method

-(void)onPlus:(Tile *) set
{
    NSString *plus = @"+";
    [set setVal:plus];
}

-(void)onMinus:(Tile *) set
{
    NSString *minus = @"-";
    [set setVal:minus];
}

How to pass the object tile to the method?? Or it have another way to make it??


Solution

  • CCMenuItemImage inherits from CCNode, which has a void* userData property. If you assign tile to userData, you could fetch it back from the (id)sender in your onPlus/onMinus methods.

    plusBtn = [CCMenuItemImage itemFromNormalImage:@"plus.png" selectedImage:@"plus.png"     target:self selector:@selector(onPlus:)];
    plusBtn.userData = (void*)tile; // You may need a bridge cast in ARC
    minusBTn = [CCMenuItemImage itemFromNormalImage:@"minus.png" selectedImage:@"minus.png"      target:self selector:@selector(onMinus:)];
    minusBTn.userData = (void*)tile;
    
    -(void)onPlus:(id)senderObj {
        CCNode *sender = (CCNode*)senderObj;
        Tile *myTile = (Tile*)sender.userData; // Again you may need a bridge cast here
    }