App was crashing when calling delete game instance on iOS

Hi everyone,

For some reasons, I have to modify some codes to delete the game instance on the native side:

  • Create a button in the main view, if user click this button I will create Cocos Creator game instance.
  • In Creator Game view, I create a close game button, if user clicks a close button I will delete Cocos Creator game instance and back to the main view.
//this code used to create game
game = new Game(height);
game->init();
//-------------------------------------------
//this code used to delete game
delete game;
game = nullptr;

But the app was crashing at ScriptEngine.cpp file:

void ScriptEngine::cleanup() {
     //....
    _isolate->Dispose(); //crash here
}

Or somtimes it was crashing in Application.cpp file:

void Application::restartVM() {
    //........
    init(); //crash here
}

I have to try to remove that line and see the app didn’t being crashing anymore, but the memory (I’m not sure which part of memory) was not free anymore.
Please note that does not occur 100%, it’s just about 50% rate after several create then delete times (by click create game button in a main view and click close game in a game view).

I also modified some native code in the cocos2d library to make it runnable.

//jsb_global_init.cpp
void jsb_init_file_operation_delegate() {
    static se::ScriptEngine::FileOperationDelegate delegate;
    if (!delegate.isValid()) {
        //......
        //se::ScriptEngine::getInstance()->setFileOperationDelegate(delegate); //remove here
    }
    se::ScriptEngine::getInstance()->setFileOperationDelegate(delegate); //move here
}

//Application-ios.mm
Application::~Application() {
     //.....
     cc::middleware::MiddlewareManager::destroyInstance(); //add
}

I attach my code for you to debug easier here: Demo
What I did in this Demo:

  • Modified AppDelegate.mm, ViewController.mm
  • Add function to call Objective C from JS:
    onCloseBtnClick()
    {
        jsb.reflection.callStaticMethod("AppDelegate", "closeGame:", "none");
    }
  • Attach files that contain some native code in cocos2d library as I mentioned above (inside _engine_modified_files folder)

I’m using Cocos Creator 3.1.1, Xcode version 12.5
Please take a look and give me some advice.
Best Regards!