开发者

Objective C, C++ and sending messages from a view controller to app dlegate

开发者 https://www.devze.com 2023-02-10 09:19 出处:网络
I have a C++ module I am using in my AppDelegate class. This all works fine. Now I need to talk to my appDelegate from my viewController, and this is causing problems.

I have a C++ module I am using in my AppDelegate class. This all works fine. Now I need to talk to my appDelegate from my viewController, and this is causing problems.

I cannot include AppDelegate in my ViewController class and 开发者_StackOverflow社区use [[UIApplication sharedApplication] delegate]. If I try, compiler goes berserk when it reaches c++ included in AppDelegate. If I rename my ViewController to .mm then it tries to parse AppDelegate.mm as c++.

Is there a way around this? Can I somehow dispatch an event from my ViewControler?


Wrap the C++ bit in

#ifdef __cplusplus__
...
#endif

Or rename the view controller source file from .m to .mm. Then it will be compiled as Objective C++.


If I rename my ViewController to .mm then it tries to parse AppDelegate.mm as c++.

that's not right. by default, the translation should (in this case) be treated as objc++. have you overridden this default behavior? i say this because i use a ton of objc++ -- it works/builds well.

anyhow... let's assume you have to work around this (which you shouldn't). this is useful because it can be better to abstract c++ from other sources (which may not be translated as c++ or objc++).

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

now objc clients may use via -[MONObject manipulateTheDataWithThisString:]. of course, you can always use C wrappers, if you prefer.


Go to project settings and try to change the 'Compile Sources As' to Objective-C++

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号