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

I need to mix Objective-C and C ++. I would like to hide all C ++ objects inside one class and keep all others equal to Objective-C. The problem is that I want some C ++ classes to be instance variables. This means that they should be mentioned in the header file, which is included by other classes, and C ++ begins to spread to the entire application. The best solution I could come up with is as follows:

#ifdef __cplusplus
#import "cppheader.h"
#endif

@interface Foo : NSObject
{
    id regularObjectiveCProperty;
    #ifdef __cplusplus
    CPPClass cppStuff;
    #endif
}

@end

It works. The implementation file has an extension mm, so it compiles as Objective-C mixed with C ++, #ifdefunlocks C ++ material and there we go. When some other, purely Objective-C class imports the header, the C ++ stuff is hidden, and the class does not see anything special. It seems like a hack, is there a better solution?

+5
source share
5 answers

This sounds like a classic use for the / @ protocol interface. Define the objective-c protocol for the API, and then provide an implementation of this protocol using the Objective-C ++ class. Therefore, customers only need to know the protocol, not the implementation header. Therefore, given the initial 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 <NSObject>

// Foo methods here
@end

Foo

@interface Foo : NSObject <IFoo>
{
    id regularObjectiveCProperty;
    CPPClass cppStuff;
}

@end

id<IFoo> Objective-C ++. , Foo .

+8

. . , ++.

, , void * , .

, Objective-C id.

+3

- , Objective ++? Compile Sources As: Objective ++ ( .cpp .m .mm). ++ Objective C.

++

? Objective C- C/Objective C- , , ++. .

, : () clang ++; ( ) C ++, C.

+1

, - , Objective++, , ++ .

0

, . , , , . ifdefing , forward-declare ,

struct CPPClass;

ivar, init/dealloc new/delete . , ++ ivars , / .

See this topic for more details and further links to information, including a podcast that discusses ObjC ++ in detail: Can I separate the main C ++ function and classes from Objective-C and / or C in compilation and link?

0
source

All Articles