简体   繁体   中英

Objective C and Objective C++

C files can be modified from .c to .m files and can be called from other Objective C files ( .m files).

C++ files can be modified from .cpp to .mm files and can be called from other Objective C++ files ( .mm files).

.m files can be called from .mm files . But .mm files cannot be called from .m files .

Is Objective C++ coding necessary in iPhone development as UI will be in Objective C and any other protocols implemented can't be Objective C++ as this (protocols written) will be called from the UI which is written Objective C .

In what scenario is this Objective C++ coding used?

Objective-C++ is used whenever you want to mix Objective-C code and C++ code.

Your statement that ".mm files cannot be called from .m files" is not true. If you put C++ in the header then you can't call it from a pure Objective-C file, but you can have a purely Objective-C interface for a class that has an implementation that uses C++. A common example is wrapping an existing C++ class (perhaps some existing library) as an Objective-C class.

.m files can be called from .mm files. But .mm files cannot be called from .m files.

Not sure what you mean by this, but I think it's wrong.

The "Objective" part of Objective-C(++) is the same in both languages. It doesn't matter whether the implementation is Objective-C or Objective-C++, the objects will be fully interoperable.

What does matter is the header file in which the interface is declared. For instance:

@interface Foo
{
   CPPFoo myFoo; // A C++ object
}

@end

can't be included in a normal Objective-C .m file because C++ classes are illegal in C. One way to get around this is to use forward declarations and pointers eg

#if defined __cplusplus
class CPPFoo;
#else
typedef struct CPPFoo CPPFoo;
#endif

@interface Foo
{
   CPPFoo *myFoo; // NOTE: a pointer to a C++ object
}

@end

You need to new the pointer in -init and delete it in -dealloc/-finalize


Is Objective C++ coding necessary in iPhone development

No. I used to think (coming from a C++ background) that it would be best to use C++ everywhere and Objective-C only in the UI. However, it didn't take long for me to realise that Objective-C's object model is better than that of C++. So now I would consider C++ in only two cases:

  • when interfacing to libraries that were written in C++
  • if performance is important and you need an built in Object model (ie you don't want to use pure C)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM