Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory management of Objective-c object in c++ class

I am writing some iOS application and facing the decision whether to include objective-c object in a c++ class. After hours of search on the internet I found discussions of using (sometimes people use 'wrapping' instead of 'using') c++ class in objective-c are abundant while the opposite is quite limited. So my first question is, is it considered appropriate (and sometimes even necessary/convenient) to have objective-c data member in c++ class?

If this is a quite normal practice in writing iOS app, with regard to memory, how do I manage the objective-c data member in c++ class, 1) using ARC and 2) using MRC? In particular, is there any rule of thumb that I should know in order to correctly writing constructor and destructor for the c++ class that has objective-c member?

like image 343
Newbie indeed Avatar asked Oct 23 '25 15:10

Newbie indeed


1 Answers

Yes, you can do this. It's not unusual.

  1. In ARC: You just use it and it works. Note that if you put an Objective-C data member inside of a class with no constructors or destructors (a "POD" class), you will get a warning because bad things will happen if that definition is imported into both ARC and MRC code. The solution if that's the case is to add a dummy constructor or destructor.

  2. In MRC: You need to retain and release it following normal MRC memory management rules for instance variables. i.e. if you assign to it, make sure to release the previous value and retain the new value. In the destructor of the class (add a destructor if there isn't already one), you need to release it. Also, in the constructor, make sure to initialize the object pointer (either to nil or some other value), because pointers in C/C++ are not automatically initialized.

like image 73
newacct Avatar answered Oct 26 '25 11:10

newacct



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!