2011-02-15 63 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包装器。

相关问题