Yes, yours self is retained in CppHelper constructor.
I don't love ARC for making simple pointers strong.
You can define __weak MYClass * _parent;
to avoid retain cycle.
Also why not use abstract interfaces of objective-C: @protocol
`s?
Question
I am integrating a C++ library to an iOS app (Objective C) which uses abstract classes to implement an event-handler pattern.
In order to receive the events, I need to implement a C++ class. Unless I'm missing something, I've been implementing C++ classes to implement the abstract interfaces, and then keeping an instance to the Objective-C class, so I can call selectors on it.
Here's an example
@implementation MYClass : NSObject
{
CppHelper * _helper;
}
- (id)init
{
if(self = [super init])
{
_helper = new CppHelper(self);
}
}
- (void)dealloc
{
delete _helper;
}
@end
...
class CppHelper : public AbstractLibraryInterface
{
private:
MYClass * _parent;
public:
CppHelper(MYClass * objCParent)
: _parent(objCParent)
{ }
onEvent()
{
[_parent handleEvent];
}
};
My question is, does passing self
via the C++ constructor create a strong ARC reference, such that my ObjC classes will be holding onto themselves?
Would using __bridge void*
and storing the ObjC class as void*
alleviate this problem? The lifetime of the C++ class is meant to be tied to the parent ObjC class.
Thanks!
Solution
Yes, yours self is retained in CppHelper constructor.
I don't love ARC for making simple pointers strong.
You can define __weak MYClass * _parent;
to avoid retain cycle.
Also why not use abstract interfaces of objective-C: @protocol
`s?