Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

ios - Swift Package and main app Target doesn't share the same Singleton

I'm trying to do something using singletons. I have a singleton class inside my Swift Package that I have to configure on didFinishLaunching calling foo.shared.config, in order to use it INSIDE my package. The thing is, that when a code inside my package runs, the foo.shared is a different instance. It's like my App creates a instance for foo.shared and my Package creates another, like they don't share the same global objects.

Some code:

Inside the package:

public class foo {
    
    public static let shared = foo()
    
    internal var credentialProvider: CredentialProvider? = nil
    
    public func config(_ provider: CredentialProvider) {
        
        self.credentialProvider = provider
    }
}

Using it inside my package like:

When debugging here, the foo.shared points to a different instance than the one used on the following snippet, hence, returning nil.

guard let token = foo.shared.credentialProvider?.accessToken else {
       
       return
}

Initializing inside didFinishLauching:

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    ...

    let myCredentialProvider = MyCredentialProvider()
    foo.shared.config(myCredentialProvider)
    ...
    
 }

MyCredentialProvider is defined inside the target app, but it's superclass is inside the Package:

public class MyCredentialProvider: CredentialProvider {

    public init() { }

    public var accessToken: String? {
        get {
            return someManager.shared.user.accessToken
        }
    }
}

I really need some directions on this because I can't fine any reference stating that singletons inside libraries share different resources. The same app uses other packages as singletons that does not share the same problem and works as expected. I really don't need to be using singletons... what I really need, is something that works on this package that makes it loosely coupled with the App itself. I tried to check on Dependency Injection using property wrappers but the storage would probably have the same problem as the App and the package would create totally different instances for it.

Thanks in advance!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...