I've written a few small programs in Objective-C (for the iPhone) but ultimately I want to write my programs mainly in C++. (I just find it a lot easier.)
If this is true, how would I:
- Ma开发者_StackOverflownage memory in C++? (Does C++ have a release-like command I need to use?)
- Intermix C++ and Objective-C coding? (Or even, should I?)
- Take a C++ object, like a string, and convert it into an NSString?
Thank you! Derek
Yes. C++ has a
delete
keyword, but it only applies to objects you've created withnew
(which, for idiomatic C++ code, is not every object). C++ also doesn't have built-in reference counting, just pure ownership.If you make a source file with a
.mm
extension, it compiles as Objective-C++, which lets you intermix Objective-C and C++ code.For a string, you can call
std::string::c_str()
to get a string that you can pass into+[NSString stringWithUTF8String:]
.
My two cents: if you feel that C++ is a lot easier than Objective-C and you don't know anything about memory management in C++, you should try to spend a fair amount of time learning pure C++; it's extremely easy to shoot yourself in the foot in C++ if you don't know what you're doing.
Manage memory in C++? (Does C++ have a release-like command I need to use?)
c++ uses new
and delete
. specifically, c++ programs prefer to use scope-bound-resource-management (SBRM). managing dynamic allocations is dead easy when you use these containers. reference counting, however, is not currently built into the language -- you can use boost www.boost.org for more advanced pointer containers, including those which offer reference counting.
Intermix C++ and Objective-C coding? (Or even, should I?)
you can easy accomplish by using the extension .mm
or .M
, or by using a compiler flag. note that you should not just enable everything as objc++ -- this will hurt your build times. also note that there are a few restrictions, including the inability to subclass c++ types as objc types and vice-versa. another important flag which any sane c++ dev would enable is the one which generates c++ constructor/destructor calls when you use c++ types as variables in your objc classes. otherwise, you'll just crash, be forced to use pimpl, or have to manually construct/destruct all your c++ instances (as ivars in objc types). this means these types you use will all need default constructors. you can intermix the languages, it's fine to do this if it is your preference. there are a few more notes on mixing them in apple's docs, but those are the important ones... oh, and be careful to quarantine your exceptions (which you must also do with objc).
Take a C++ object, like a string, and convert it into an NSString?
see John Calsbeek's response
good luck
精彩评论