Calling a C ++ Object Method from an Objective-C Child

I have Objective-C ++ code that I am trying to get from an Objective-C object to call a method inside a C ++ object. I am very new to Objective-C, so I can do it all wrong.

Example:

@interface KnobClass {
}
-(void)Event;
@end

class DoorClass {
    public:
    KnobClass * knob;
    void start() { knob = [[KnobClass allocate] init]; }
};

class AlarmClass {
    public:
    void Alert();
};

class HouseClass {
    public:
    DoorClass door;
    AlarmClass alarm;
};

int main() {
    //...
    HouseClass house;
    house.door.start();
    //...
    return 0;
}

The method is [house.door.knob Event]generated in the event, and I want it to be able to call house.alarm.Alert(). But I am confused how to do it right. Can anyone suggest a way to do this?

+3
source share
1 answer

I am also learning Objective-C. This works in gcc 4.3.3:

#import <Foundation/Foundation.h>

class AlarmClass {
    public:
    void Alert() {
        printf("Alert!\n");
    }
};    

@interface KnobClass: NSObject {
    AlarmClass *alarm;
}
-(void)Event;
-(id)initWithAlarm:(AlarmClass*) alarm;
@end

@implementation KnobClass: NSObject

-(id)initWithAlarm:(AlarmClass*) a
{
    self = [super init];
    alarm = a;
    return self;
}

-(void)Event
{
    alarm->Alert();
}
@end

class DoorClass {
    public:
    KnobClass * knob;
    void start(AlarmClass *a) {
        knob = [[KnobClass alloc] initWithAlarm: a];
    }

    void doEvent() {
        [knob Event];
    }
};

class HouseClass {
    public:
    DoorClass door;
    AlarmClass alarm;
};

int main(int argc, const char *argv[]) {
    //...
    HouseClass house;
    house.door.start(&house.alarm);
    house.door.doEvent();
    //...
    return 0;
}
+2
source

Source: https://habr.com/ru/post/1731781/


All Articles