Dynamically loading a class with -classNamed: fails randomly

I have an app that dynamically loads classes using the following code ...


Class cls = [[NSBundle mainBundle] classNamed:s];


This worked since iOS4 but recently failing about 50% on the iOS Simulator, but some reports on stackoverflow hint it hits real devices, too.

Does anyone know a workaround?


LittleNapoleon* dummy = [LittleNapoleon class];
NSLog(@"%@",NSStringFromClass(dummy));
Class cls = [[NSBundle mainBundle] classNamed:s];
NSAssert(cls != nil, @"classNamed: %@ returned nil!", s);


This fails even if the class is successfully loaded in the code! Output ...


LittleNapoleon

'classNamed: LittleNapoleon returned nil!'

References: http://stackoverflow.com/questions/39794424/classnamed-in-ios-10-on-ipad-air-2

Replies

Please post your bug report number when discussing iOS bugs, and file bug reports in the Bug Reporter.


http://developer.apple.com/bug-reporting/

I will not waste my time filing iOS bugs anymore, only tech support incidents do work.

I have bugreports open since 2011 that did not get any acknowlegement.

Here’s what I did:

  • In Xcode 8.1, I created a new Objective-C project from the Single View Application template.

  • I added a new Objective-C class called

    LittleNapoleon
    , using the Cocoa Touch Class template.
  • I modified

    -[ViewController viewDidLoad]
    to load the class; the code you posted doesn’t actually compile, so I modified it as shown below. I also added an include of
    LittleNapoleon.h
    to the top of the file.
  • I ran the app ten times on the iOS 10.1 simulator. It worked every time, producing the following output.

    2016-12-13 15:40:40.772 xxoi2[6368:438372] s = LittleNapoleon
    2016-12-13 15:40:40.773 xxoi2[6368:438372] cls = LittleNapoleon


  • I also ran it a few times on an iOS 10.1.1 device and that works fine as well.


    I’m not sure what’s happening with your project, but this seems to be working for me. Perhaps you can try repeating the steps I’ve described above to see if the problem is related to your environment or your actual project.


    Share and Enjoy

    Quinn “The Eskimo!”

    Apple Developer Relations, Developer Technical Support, Core OS/Hardware

    let myEmail = "eskimo" + "1" + "@apple.com"



    Class dummy = [LittleNapoleon class];
    NSString * s = NSStringFromClass(dummy);
    NSLog(@"s = %@", s); 
    Class cls = [[NSBundle mainBundle] classNamed:s]; 
    NSLog(@"cls = %@", cls);