iosswiftcocoapodssingleton

Why does the singleton class in iOS, when combined with multiple dynamic frameworks, result in multiple instances?


The main project ModuleDemo depends on ModuleA, ModuleB, and ModuleC. The description of the entire project's Podfile is roughly as follows:

platform :ios, '13.0'
use_frameworks! :linkage => :static

workspace 'Module.xcworkspace'

def downloader
  pod 'Downloader'
end

def treasureBox
  pod 'TreasureBox'
end

abstract_target 'ModuleDemo' do

    target "ModuleDemo" do
        project 'ModuleDemo/ModuleDemo.xcodeproj'
    downloader
    end

    target "ModuleA" do
        project 'ModuleA/ModuleA.xcodeproj'
    downloader
    treasureBox
    end

    target "ModuleB" do
        project 'ModuleB/ModuleB.xcodeproj'
    downloader
    treasureBox
    end

    target "ModuleC" do
        project 'ModuleC/ModuleC.xcodeproj'
    downloader
    treasureBox
    end
end

Through testing, it was found that since each module generates a dynamic framework, Downloader will be copied into each module. After the program runs, it is discovered that there are multiple instances of the singleton in Downloader in the memory. May I ask why this is the case? I understand that a singleton is supposed to ensure that there is only one instance within a single process, isn't it?


Solution

  • You have multiple targets here, you can try to use a single target plus dependencies You can modify it like this in your Podfile.

    target "ModuleDemo" do
      pod 'downloader'
      pod 'treasureBox'
      pod 'ModuleA', :path => 'ModuleA'
      pod 'ModuleB', :path => 'ModuleB'
      pod 'ModuleC', :path => 'ModuleC'
    end
    

    In ModuleA/ModuleA.podspec, Module B and Module C are similar to Module A

    Pod::Spec.new do |s|
      s.name             = 'ModuleA'
      ...
      s.dependency 'downloader'
      s.dependency 'treasureBox'
    end