问题
I'm having a hell of a time with the CCMenu class. To create a menu with this class it forces you to call a method called initWithItems, which takes a va_list. I need to generate this list at runtime, and I read that creating a C array and passing that can function just as va_list does under the covers, only it is failing.
I have an NSArray of items I want in the va_list, and these items are a SUBCLASS of CCMenuItem, the class that menuWithItems is expecting in the va_list. If you hardcode this list at compile time, it works fine, but my attempt to create this list dynamically is not working. What is wrong with this? MenuItemButton is a CCMenuItem subclass.
NSArray *menuItems = [self getMenuItemsArray]; // Returns an NSArray of MenuItemButtons
MenuItemButton *argList = (MenuItemButton *)malloc( sizeof(MenuItemButton *) * [menuItems count] );
[menuItems getObjects:(id *)argList];
CCMenuAdvanced* menu = [CCMenuAdvanced menuWithItems:argList];
This crashes at runtime, BAD_ACCESS. I know the va_list is supposed to be null terminated, I don't know if that is the case with my code here after calling getObjects, or if that is even the problem.
回答1:
You could simply initialize the menu using nil. For example,
CCMenu * myMenu = [CCMenuAdvanced menuWithItems:nil];
Then say you have a dynamic list of strings that you loaded at runtime, try....
// replace this with a dynamically loaded array of items...
NSArray* dynamicArray = [NSArray arrayWithObjects:@"red", @"blue", @"green", nil];
for (NSString* item in dynamicArray)
{
CCMenuItem *menuItem = [CCMenuItemFont itemFromString: item target: self selector:@selector(menuCallback:)];
[myMenu addChild:menuItem];
}
回答2:
va_list
isn't always an array. With 32-bit gcc, it is, with 64-bit it isn't. Don't rely on it.
va_list
is generated by a function that gets a variable number of arguments:
#include <stdarg.h>
void f(int x, ...) {
va_list va;
va_start(va, x);
function_that_wants_va(va);
va_end(va);
}
void g(void) {
f(1,2,3,4);
}
来源:https://stackoverflow.com/questions/9283382/how-do-you-properly-create-a-va-list-dynamically-at-runtime-for-cocos2d-ccmenu-m