John John - 6 months ago 11
iOS Question

Why does not executing the following code cause it to crash?

I have an app that uses Admob. But since I am supporting versions of iOS 5 and above, I make sure that I don't call Admob code in versions below iOS 6 by doing the following:

if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_5_1) {
int j = 2;
j++; //This is just some code so I can use breakpoints for testing.
NSLog(@"Google Mobile Ads SDK version: %@", [GADRequest sdkVersion]); //Commenting out the line prevents the crash
}


I am testing on iOS 5.1.1. Now if I comment out the NSLog, line, the app works without problem. But if I uncomment it the app crashes almost immediately within the main method:

int retVal = UIApplicationMain(argc, argv, nil, @"AppController");

I guess its not crashing when it is commented out because the compiler "optimises out" the code since its not used. But then what is the correct way to make sure the code isn't used, and the app doesn't crash ?

EDIT: I edited the code, the if block is not optimised out:

int j = 2;

if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_5_1) {
j++; //This is just some code so I can use breakpoints for testing.
NSLog(@"Google Mobile Ads SDK version: %@", [GADRequest sdkVersion]); //Commenting out the line prevents the crash
}else{
j--;
}

NSLog(@"%d",j);


The output is "1", so the code in the else block executes. So even thought the function call
[GADRequest sdkVersion]
is not made, why does it crash ? Again, if I comment out the function call the app does not crash.

Answer

One possibility that is consistent with what you're describing is that linking to AdMob causes the crash. Sending a message to the GADRequest class in your code causes it to link to the GADRequest class, whereas if you didn't, it wouldn't link to it.

Why does linking to AdMob cause the crash? Most likely it's because AdMob links to several system frameworks, some of which may not exist on iOS 5 (e.g. AdSupport framework), so when it tries to dynamically link to them on app startup, the dynamic linker crashes.

I'm not sure what you can do. Maybe you can try explicitly linking to the system frameworks that AdMob use as "optional" in Xcode? (I haven't tested it.)

Otherwise, you could downgrade to a version of AdMob that supports iOS 5 (according to the release notes, any version before 7 should do).

Comments