cocos2d-iphoneautomatic-ref-countingkobold2d

passing userData via ccmenuitem with ARC enabled


I'm trying to pass an NSString via a menuitem using the following code

CCMenuItem * buyButton = [CCMenuItemLabel itemWithLabel:buyLabel target:self selector:@selector(buyItem:)];
buyButton.userData = (__bridge void *)((NSString*)(itemName));

to the following selector

-(void) buyItem:(CCMenuItemLabel*)sender {
   NSString * itemName = (NSString *)sender.userData;
     }

but i'm crashing in the selector. I am using cocos2d with arc enabled, hence the bridge in the userdata assigment. (kobold2d). any ideas?


Solution

  • Your actual crash problem is this:

    NSString * itemName = (NSString *)sender.userData;
    

    Look over it, what are you casting here? Right: you're casting sender to NSString* and then you're sending sender (the CCMenuItemLabel) a userData message. BAM!

    Brackets to the rescue:

    NSString * itemName = (__bridge NSString *)(sender.userData);
    

    Also, why make it overly complicated when there's userObject?

    buyButton.userObject = itemName;
    

    userObject is an id type and requires no bridge casting, userData is void* and requires bridge casting