Null Reference Exception in SharedObject [cpp] [SOLVED]

Attempting to create a SharedObject results in a crash on line 166 of

Lib.application.onExit.add (application_onExit);

Using OpenFL 3.6.0 and the most recent build of Lime.

Either Lib.application is null, or Lib.application.onExit is null. You can test which, but (spoiler alert) only the first one is possible.

This value is defined very early on, but it seems you’re running code before that happens.

I only know one way to run code that early: run it in a static initializer. Let me guess, your implementation looks something like this?

public static var save:SharedObject = SharedObject.getLocal("name");

Code like that will be run as soon as your class is imported, even before the application’s main() function is called. The easiest solution is lazy initialization:

public static var save(get, null):SharedObject;
private static function get_save():SharedObject {
    if(save == null) {
        save = SharedObject.getLocal("save");
    return save;

This means it won’t be created until your code first needs it, which won’t happen until after Lib.application is defined.

Aha, that’s exactly what’s going on. Interestingly, the code inside SharedObject looks like it uses lazy initialization so it didn’t occur to me that order-of-initialization would be an issue. Thanks a lot, that’s one big issue taken care of.