2011-12-22 35 views
3

我有.mm文件,其中我有一些C++函數和幾行目標c。混合問題目標C和C++在單個文件中

例如,

void display() 
{ 
.... 
.... 
} 

void doSomthing() 
{ 
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 50)]; 
[button addTarget:??? action:@selector(display) ....] 

[rooView addSubView:UIButton]; 
} 

我不知道如何調用在同一個mm文件中定義的顯示功能嗎? 什麼是我的addTarget? (自己/這在我的情況下不工作)

+0

目標是將接收'display'消息的對象。 – 2011-12-22 09:09:24

回答

2

你需要一個Objective-C類和一些方法來包裝你的C++函數調用。

@interface WrapperClass : NSObject 

-(void) display; 

@end 

void display() 
{ 
.... 
.... 
} 

@implementation WrapperClass 

-(void) display 
{ 
    display(); 
} 

@end 

static WrapperClass* wrapperObj = nil; 

void doSomthing() 
{ 
    if (wrapperObj == nil) 
    { 
     wrapperObj = [[WrapperClass alloc] init]; 
    } 

    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 50)]; 
    [button addTarget: wrapperObj action:@selector(display) forControlEvents: whatever]; 
    [rooView addSubView:UIButton]; 
} 
4

你不能使用@selector()引用一個函數,你只能用它來引用一個objective-c方法。

此外,UIButton類在單擊時無法執行函數調用。它只能執行一個objective-c方法。

但是,您可以 「包裝」 Objective-C的方法,圍繞功能:

- (void)display:(id)sender 
{ 
    display(); 
} 

允許這樣的:

[button addTarget:self action:@selector(display:) ....]; 

但是,如果你正在寫自己的顯示器()函數,然後你也可以把它的內容放在顯示方法中。

+0

如果我在ddeclare毫米文件目標c函數,用於離 - (無效)顯示 { } 它顯示如下錯誤 「缺少方法聲明上下文」 –

+1

@chetan:也需要一個Objective-C類也發送顯示消息。你可以在.mm文件中定義它。 – JeremyP