I have the following code in my C++/Objective-C app:
#import <YandexMobileAds/YandexMobileAds-Swift.h>
@class AdHook;
namespace MyApp
{
class AdHolder
{
public:
AdHolder(IosInterstitialAd* cpp_ad);
AdHook* m_hook;
};
}
using namespace MyApp;
@interface AdHook : NSObject <YMAInterstitialAdLoaderDelegate, YMAInterstitialAdDelegate>
{
@public IosInterstitialAd* m_cppAd;
@public YMAInterstitialAdLoader* m_loader;
@public YMAInterstitialAd* m_interstitialAd;
}
@end
@implementation AdHook
- (id)initFromCpp:(IosInterstitialAd *)cpp_ad
{
if (self = [super init])
{
m_cppAd = cpp_ad;
m_interstitialAd = nil;
m_loader = [[YMAInterstitialAdLoader alloc]init];
m_loader.delegate = self;
}
return self;
}
AdHolder::AdHolder(IosInterstitialAd* cpp_ad)
{
[YMAMobileAds enableLogging];
m_hook = [[AdHook alloc]initFromCpp:cpp_ad];
}
void SomeOtherClass::load()
{
NSLog(@"IosInterstitialAd::load()");
YMAAdRequestConfiguration* configuration = [[YMAAdRequestConfiguration alloc]initWithAdUnitID:@"demo-interstitial-yandex"];
[m_holder->m_hook->m_loader loadAdWithRequestConfiguration:configuration];
}
I create an instance of AdHolder
class in C++ code and AdHolder
‘s constructor creates an instance of Objective-C class AdHook
that in its turn crates its internal Objective-C objects.
But I do not understand well enough what is the lifetime of m_hook
? And I suspect that it is deleted at some point, because when I try to access m_hook->m_interstitialAd
from YMAInterstitialAdLoaderDelegate
callback I get a wrong value and the app crashes.
Is m_hook a strong reference? If it is not how to make it strong?
EDIT1
Tried to randomly add retain
call to various objects in my app and made the app work by adding retain
call to AdHook::m_interstitialAd
:
- (void)interstitialAdLoader:(YMAInterstitialAdLoader * _Nonnull)adLoader didLoad:(YMAInterstitialAd * _Nonnull)interstitialAd
{
NSLog(@"IosInterstitialAd::YMAInterstitialAdLoader::didLoad, %@", interstitialAd);
m_interstitialAd = [interstitialAd retain];
m_interstitialAd.delegate = self;
}
at least my app stopped crashing when I access m_interstitialAd
.
So the question probably is if AdHook::m_interstitialAd
a strong reference?
7
The issue likely stems from m_hook not being a strong reference in your C++ class. In Objective-C/C++ interop, plain pointers don’t imply ownership. To create a strong reference, modify your AdHolder class to use a pointer to a pointer (AdHook** m_hook;). In the constructor, allocate it with m_hook = new AdHook*; *m_hook = [[AdHook alloc] initFromCpp:cpp_ad];. Add a destructor to clean up: if (m_hook) { [*m_hook release]; delete m_hook; }. When accessing, use (*holder()->m_hook)->m_loader. This ensures the AdHook object isn’t deallocated unexpectedly. Also, verify that the AdHolder instance itself remains valid when you’re accessing m_hook, as its premature destruction could lead to crashes.
3