Swift singleton is used with init (coder :)

I am trying to make a reusable UI component using a singleton, so it is always used by the same instance used by the application when the UI component is displayed (only one of them can be shown at a time).

So, I created a simple UIView subclass and defined the sharedInstance path of the Swift 1.2. Here's the code:

import UIKit

class MyView: UIView {
    static let sharedInstance = MyView()
}

      

Thing is, I was wondering if there is a way to make this sharedInstance

usable when the view is called by the storyboard (so through the method init(coder:)

).

In ObjC this will be pretty easy as init methods can just return the desired object, but in Swift I really don't know if this is something (since Swift init doesn't return an object).

EDIT . Just to add some context (some people don't understand WHY I would like to do this). I am trying to avoid a given UI component on which I cannot control all the available memory.

This component is a MKMapView that does not release memory that is required after it has been unreasonable. I tried a few things, but no one gave me back all the memory they got when the MKMapView was created.

So, I tried to use the same MKMapView instance everywhere to avoid having to use more memory used.

I asked a question so you have a general answer to the question of returning a sharedInstance when init (coder :) is called so that I can just use my component from any storyboard file without having to use the code to use sharedInstance.

+3


source to share


2 answers


One way is to simply grab the scene directly from the storyboard:



static let sharedInstance = (UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("identifier") as! UIViewController).view

      

+1


source


Try awakeAfter (using :). This method is a good place to check if this is the one you want and replace it. The return sharedInstance and self will be replaced.



+1


source







All Articles