5

I made a Swift framework called SharedLocation with a Swift singleton class "SharedLocationManager" inside of it like so:

public class SharedLocationManager: CLLocationManager, CLLocationManagerDelegate
{
public class var sharedInstance: SharedLocationManager {
    struct Static
    {
        static var onceToken : dispatch_once_t = 0
        static var instance : SharedLocationManager? = nil
    }
    dispatch_once(&Static.onceToken)
    {
            Static.instance = SharedLocationManager()
    }
    return Static.instance!
}

public override init()
{
    //do init stuff

}

A shared instance of this class should be accessable from my iOS app (written in Objective-C) and my WatchKit Extension (written in Swift).

i imported the framework in the iOS ViewController like so:

 @import SharedLocation

and in the Watch InterfaceController like so:

import SharedLocation

I am able to get an instance of the singleton class in both targets BUT these are different instances (init() is called twice). When I access the sharedInstance inside the WatchKit Target everything works fine and I get the same instance every time.

Is it even possible to have a singleton class with multiple targets?

iVentis
  • 993
  • 6
  • 19
  • Both App, and WatchKit run on different instances, so you have two different instances of singleton classes, you can't access one from another. – iphonic Mar 24 '15 at 11:25
  • Is there any workaround?? – iVentis Mar 24 '15 at 11:31
  • Why do you want to do this? Want to access location register in the app from watchkit? – iphonic Mar 24 '15 at 11:32
  • 1
    It's a running app and I want to start a run on the watch and then be able to continue the run on the phone, so I wanted to do all location based services inside of a public class where both targets can access the same run data and didUpdateLocation method – iVentis Mar 24 '15 at 11:35
  • Its not possible this way may be a common file in the group folder can help.. See one of my answer here http://stackoverflow.com/a/27796037/790842 – iphonic Mar 24 '15 at 11:37
  • and what do you suggest to store inside that common file? – iVentis Mar 24 '15 at 11:41
  • run data, ofcourse? or the data you want to use in the watchkit extension? – iphonic Mar 25 '15 at 04:40

1 Answers1

2

No, it is not possible to have a single instance of a singleton shared between your extension and app. Your WatchKit extension and your iOS app are running in different processes. You can save data to a shared group folder if you want to access that data in your extension and your app. You can also use frameworks like MMWormhole if you want to communicate between your extension and app.

Stephen Johnson
  • 5,293
  • 1
  • 23
  • 37