2011-02-15 62 views
1

我在我的AppDelegate類中使用了一個C++模塊。這一切工作正常。現在我需要從我的viewController與我的appDelegate進行交談,這導致了問題。Objective C,C++和從視圖控制器發送消息到應用程序dlegate

我不能在我的ViewController類中包含AppDelegate並使用[[UIApplication sharedApplication]委託]。如果我嘗試一下,當它到達AppDelegate中包含的C++時,編譯器會變得瘋狂。如果我將ViewController重命名爲.mm,那麼它會嘗試將AppDelegate.mm解析爲C++。

有沒有辦法解決這個問題?我可以以某種方式從我的ViewControler發送一個事件嗎?

回答

0

轉到項目設置,並嘗試從.M改變「編譯來源」來的Objective-C++

2

包裹C++位

#ifdef __cplusplus__ 
... 
#endif 

或重命名視圖控制器源文件。毫米。然後它將被編譯爲Objective C++。

+0

corr:`__cplusplus`。另外,如果進/出可能是危險的,取決於C++類的實際使用方式。當然,在某些情況下也是可以的。 – justin 2011-02-15 15:30:57

+0

@Justin:至少在iOS/XCode上,`__cplusplus__`也可以。 – 2011-02-15 15:45:16

1

如果我將我的ViewController重命名爲.mm,那麼它會嘗試將AppDelegate.mm解析爲C++。

這是不對的。默認情況下,翻譯應該(在這種情況下)被視爲objC++。你有沒有重寫這個默認行爲?我說這是因爲我使用了一噸objC++ - 它的工作/構建得很好。無論如何,我們假設你必須解決這個問題(你不應該這麼做)。這很有用,因爲從其他源(可能不會被轉換爲C++或objC++)抽象C++可能會更好。

MONObject.h 
/* our c++ class. 
    use a forward declaration so the c/objc translations don't 
    need to see the declaration of t_mon_object_data. 
*/ 
struct t_mon_object_data; 

@interface MONObject : NSObject 
{ 
    /* similarly, use a pointer as an ivar so the c/obj translations do not need 
     to see the declaration of t_mon_object_data. 
     use new/delete in your implementation of MONObject (which is objc++) 
    */ 
    t_mon_object_data* objectData; 
} 

- (void)manipulateTheDataWithThisString:(NSString *)string; 

@end 

MONObject.mm 
@implementation MONObject 

- (id)init 
{ 
    self = [super init]; 
    if (nil != self) { 
     objectData = new t_mon_object_data; 
     if (0 == objectData) { 
      [self release]; 
      return nil; 
     } 
    } 
    return self; 
} 

- (void)dealloc 
{ 
    delete objectData; 
    [super dealloc]; 
} 

- (void)manipulateTheDataWithThisString:(NSString *)string 
{ 
    objectData->manipulateTheDataWithThisString(string); 
} 

@end 

現在objc客戶可以通過-[MONObject manipulateTheDataWithThisString:]使用。當然,如果你願意,你總是可以使用C包裝器。

相關問題