0

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?

kidnim
  • 1,477
  • 2
  • 10
  • 13

2 Answers2

5

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

CodeSmile
  • 64,284
  • 20
  • 132
  • 217
  • thanks steffen, i didn't try the proper cast you mentioned but userobject was the right move, worked great! looking fwd to seeing what you do with kobold kit! – kidnim Jul 10 '13 at 01:09
0

Try this, its working

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

 CCMenu *menu = [CCMenu menuWithItems:buyButton, nil];
 menu.position = ccp(240, 160);
 [self addChild:menu];

And buyItem function:

-(void) buyItem:(CCMenuItemLabel*)sender {
    NSString * itemName = (__bridge NSString*)sender.userData;
    printf("NSString: %s\n", [itemName UTF8String]);
}

And you will get Out put as

NSString:kidnim
Renaissance
  • 564
  • 5
  • 26
  • Your code definitely worked, thanks but unfortunately I need to set the string. I'm missing something as to why your code works perfectly but changing the userdata definition to: 'buyButton.userData = (__bridge void *)((NSString *)([NSString stringWithFormat:@"kidnim"]));' doesn't – kidnim Jul 09 '13 at 15:21
  • Unfortunately, the currently posted code isn't working for me – kidnim Jul 10 '13 at 00:50
  • the code works when its on a layer alone, but below some other code that is otherwise functioning, it bails. the other code is loading info from a plist file and creating a CCScrollLayer. it seems removing a chunk that begins with this line makes it work: ` if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]) { plistPath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"plist"]; }` but i'm using the userobject answer thanks – kidnim Jul 10 '13 at 01:12