C++ classes as instance variables of an Objective-C class

后端 未结 5 1220
轻奢々
轻奢々 2021-02-10 06:29

I need to mix Objective-C and C++. I would like to hide all the C++ stuff inside one class and keep all the others plain Objective-C. The problem is that I want to have some C++

5条回答
  •  耶瑟儿~
    2021-02-10 06:59

    This sounds like a classic use for an interface/@protocol. Define an objective-c protocol for the API and then provide an implementation of that protocol using your Objective-C++ class. This way clients need only know about the protocol and not the header of the implementation. So given the original implementation

    @interface Foo : NSObject
    {
        id regularObjectiveCProperty;
        CPPClass cppStuff;
    
    }
    
    @end
    

    I would define a protocol

    //Extending the NSObject protocol gives the NSObject
    // protocol methods. If not all implementations are
    // descended from NSObject, skip this.
    @protocol IFoo 
    
    // Foo methods here
    @end
    

    and modify the original Foo declaration to

    @interface Foo : NSObject 
    {
        id regularObjectiveCProperty;
        CPPClass cppStuff;
    }
    
    @end
    

    Client code can then work with type id and does not need to be compiled as Objective-C++. Obviously you can pass an instance of Foo to these clients.

提交回复
热议问题