2012-09-07 90 views
1

所以我創建了一個類CommonMethods與類方法:類方法中包含選擇調用另一個類的方法

+ (CCMenu *)createMenu:(NSString *)menuName atPosition:(CGPoint)position { 
    CCMenuItemImage *menuBlock = [CCMenuItemImage itemWithNormalImage:menuName selectedImage:menuName target:self selector:@selector(choose:)]; 
    CCMenu *menuBlockMenu = [CCMenu menuWithItems:menuBlock, nil]; 
    menuBlockMenu.position = position; 
    return menuBlockMenu; 
} 
我MainClass包含選擇

現在:方法,我創建了一個菜單:

CCMenu *regularBlockMenu = [CommonMethods createMenu:kbRegularBlock atPosition:position]; 
[self addChild:regularBlockMenu]; 

當我點擊菜單時,我的程序崩潰,因爲它不理解選擇器調用。我如何實現這一點?我想創建一個CommonMethods方法,因爲我會在很多類中反覆使用這個方法。

感謝您的幫助。

回答

1

你想在類MainClass中選擇一個方法嗎?如果是這樣,你需要修改你的createMenu函數。試試這個,

+ (CCMenu *)createMenu:(NSString *)menuName atPosition:(CGPoint)position forTarget:(id)target 
{ 
    CCMenuItemImage *menuBlock = [CCMenuItemImage itemWithNormalImage:menuName selectedImage:menuName target:target selector:@selector(choose:)]; 
    CCMenu *menuBlockMenu = [CCMenu menuWithItems:menuBlock, nil]; 
    menuBlockMenu.position = position; 
    return menuBlockMenu; 
} 
在MainClass

則:

CCMenu *regularBlockMenu = [CommonMethods createMenu:kbRegularBlock atPosition:position forTarget:self]; 
[self addChild:regularBlockMenu]; 

,你需要在MainClass定義-(void)choose:(id)sender;

那麼這是什麼做的是設置選擇的目標:是的實例MainClass,而不是CommonMethods。

+0

這適用於我的目的。謝謝! – Huy

+0

+1這是一個比原來的更好的解決方案! – dasblinkenlight

1

因爲在一個類的方法self指類,你不應該讓self您選擇的目標:

CCMenuItemImage *menuBlock = [CCMenuItemImage itemWithNormalImage:menuName selectedImage:menuName target:self selector:@selector(choose:)]; 
//                       HERE ------^^^^ 

相反,你應該發送的選擇,以響應該選擇對象choose:

0

你需要CommonMethods單身

@implementation CommonMethods 
static CommonMethods* globalCommonMethods = nil; 
+(CommonMethods*)gCommonMethods 
{ 
    if(!globalCommonMethods) globalCommonMethods = [[CommonMethods alloc] init]; 
    return globalCommonMethods; 
} 
-(CCMenu *)createMenu:(NSString *)menuName atPosition:(CGPoint)position { 
    CCMenuItemImage *menuBlock = [CCMenuItemImage itemWithNormalImage:menuName selectedImage:menuName target:self selector:@selector(choose:)]; 
    CCMenu *menuBlockMenu = [CCMenu menuWithItems:menuBlock, nil]; 
    menuBlockMenu.position = position; 
    return menuBlockMenu; 
} 

-(void)choose:(id)sender 
{ 
    //do stuff 
} 

現在,當你需要交流使用CommonMethods [CommonMethods gCommonMethods]

+0

不應該是'+(void)選擇:(id)sender',因爲'createMenu:atPosition:'是類方法嗎? – dasblinkenlight

+0

你不能使用類方法作爲選擇器。因爲按鈕將會調用[delegate choose:self];如果將選擇定義爲類方法,這將無法正常工作。 – Kyle

+0

但是你應該發送什麼樣的'CommonMethods'作爲選擇器的目標?如果你傳遞'self',Obj-C就不會找到你的'choose:'選擇器,因爲'self'是'CommonMethods'的'Class'對象。 – dasblinkenlight