views:

139

answers:

1

I have some Objective-C++ code that I'm trying to get events out of an Objective-C object to call a method within a C++ object. I'm very new to Objective-C, so I may be doing this 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 [house.door.knob Event] is generated on an event, and I want it to be able to call house.alarm.Alert(). But I'm confused how to accomplish this in a correct manner. Can someone suggest a way of accomplishing this?

+1  A: 

Hi, I'm learning Objective-C too. 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;
}
João da Silva
That seems to have worked. Thanks!
mike_b