0

By default as we know an objective-C project is created with automatic reference counting.

if we mix C/C++ code in a .mm file in an object-C project. C/C++ obviously has to be manually managed ie objects should be manually removed with delete etc.

If I choose ARC will that be a safe choice ? or or the manual reference counting should be a safe choice ? Furthermore, if some swift code has to be mixed with it will my choice of ARC or manual be effected in anyway ?

EMED
  • 11
  • 4

1 Answers1

0

Modern apps should use ARC for Objective-C memory management.

Very generally, your C++ memory management will have to rely on:

  1. local stack-based object creation and deletion, which will work fine in the scope of a method as long as there are no Obj-C exceptions thrown.

  2. allocated C++ objects with new/delete explicitly called.

  3. wrappers and containers that use 1 or 2.

For example, an NSValue can contain a pointer that is a C++ object created with new(), but the NSValue will not automatically delete it, so if it's a member of an Objective-C class you need to override dealloc() (when ARC frees the object) and delete the underlying C++ pointer wrapped in your NSValue object.

OTOH C++ safe-pointer wrappers declared on the stack will work as expected when they go out of scope.

Exception handling is important to understand, so search for information about Objective-C exceptions vs. C++ exceptions both here and in other tutorials and documentation. In general, try to avoid using exceptions for program flow when mixing ARC and C++ code.

This aspect of the question may mostly be answered here: Objective-C Exceptions

Also here's a thread about NSValue valueWithPointer: Does NSValue free its value when freed?

Corbell
  • 1,283
  • 8
  • 15