Since the shared singleton instance will always be around, can we safely use [unowned self] in all closures within that singleton class?
Safe to always use [unowned self] for Swift singletons?
1.4k Views Asked by SchoonSauce At
2
There are 2 best solutions below
0
newacct
On
Sure, it's safe. But that's not a good reason.
Whether you use weak references or strong references should be based on the memory management characteristics in the function you are writing. For example, if a closure is referred to strongly by the object, then the closure should capture a weak reference to the object; and that is safe since nobody else has a reference to the closure, so it only can execute while the main object is alive, etc. If there is no retain cycle, and the closure is given to a separate API so that it is not tied to the lifetime of the main object, then the closure should have a strong reference to the main object. This reasoning applies equally for singletons and non-singletons alike.
Related Questions in SWIFT
- Overlapping UICollectionView in storyboard
- Cannot pod spec lint because of undeclared type errors
- Swift code with multiple NSDateFormatter - optimization
- How do I add multiple in app purchases in Swift Spritekit?
- cellForRowAtIndexPath and prepareForSegue return different label colors
- Getting this message in my console in xcode "Ignoring restoreCompletedTransactionsWithApplicationUsername: because already restoring transactions"?
- Change background of an Accessory View in a UITableViewCell
- fade in an bounce animation subview
- Create a PFObject and PFRelation after PFUser Sign Up
- Swift 2 - Pattern matching in "if"
- How do I give inputs through NSURL
- How do I add custom cells to TableView in Swift?
- UIWebView not loading URL in simulator
- Compiler complains that 'Expression resolved to unused function' when removing index in array of functions
- Cast from 'Int?' to unrelated type 'NSNumber' always fails
Related Questions in MEMORY-MANAGEMENT
- Calling Dealloc method in sprite kit
- Allocating memory for pointers inside structures in functions
- Beginner iOS memory management
- Deleting a dynamically allocated 2D array
- DataTable does not release memory
- how to resize image properly without memory warning
- Application Verifier limits Heap Allocations by default?
- C++ assign const reference to instance variable (memory issues?)
- What memory issues may arise from a single page JavaScript/AJAX application when kept open over a period of months?
- How to increase PHP memory_limit in Debian Jessie?
- Is this correct point to free char*
- Using parse.com and having allocation memory issue
- Qt object ownership when using lambda as slot
- Any ideas why one object is not deallocated in objective-c ARC
- How do I set a buffer in a possibly recursive procedure?
Related Questions in SINGLETON
- Swift - Issue trying to access to Singleton object
- lazy loaded Singleton - will a static field call cause instantiation
- Can I access the same instance of a Service object without using Channel?
- What is the difference between a class wrapper and Java, and a singleton in Objective-C?
- Defining Macros that are equal to functions that return objects in C++
- How to create object/singleton of generic type in Scala?
- Prolog- singleton variable in branch warning
- Singleton in iOS Objective C doesn't prevent more than one instance
- visual studio cannot resolve static functions
- Unresolved external symbol (singleton class C++)
- Mage registry key "_singleton/tax/observer" already exists
- Function pointer to singleton class instance function
- trying to implement simple ostream singleton class
- Instance of Singleton null
- how can I recreate singleton class in java
Related Questions in REFERENCE-COUNTING
- What is the idiomatic way to write a linked list with a tail pointer?
- What are the reference counts of objects A and B after assigning B=A?
- LibGDX - How many references counted in AssetManager of my case?
- LibGDX - Should texture.dispose() execute first and then batch.dispose()? or no different?
- CFGetRetainCount returns 2 after creating an object, should be 1?
- Can reference counting be relied on to close a file in Python?
- Release-Consume ordering for reference counting
- Reusing Qt's QString COW / ref counting in a string registry
- How to break a direct reference cycle in CPython
- Reference counting in a collection
- Pointer casts for itk::SmartPointer?
- Querying Python runtime for all objects in existence
- pyfftw release references to arrays without destroying plan
- C++ COM client releases two different objects within one call ?! 2nd Release causes access violation
- Intrusive ref count w/ action on destruction
Related Questions in UNOWNED-REFERENCES
- Swift. unowned may only be applied to class and class-bound protocol types. weak works fine
- Safe to always use [unowned self] for Swift singletons?
- Swift Weak Reference Much Slower than Strong Reference
- Difference between unowned var something: Something! and weak var something: Something! in Swift
- Swift unowned self leaking when 'owned' by a view being presented
- Why weakifying a strong reference by using a local variable doesn't work?
- Swift - @escaping and capture list clarification
- Swift - Capture List self clarification
- Weak or Unowned or None
- Does ARC hold a count for unowned reference?
- How Unowned reference works with capture variables in Swift
- In Swift, unowned vs. weak reference
- Add [unowned self] to the closure argument Swift
- Do capture lists of inner closures need to redeclare `self` as `weak` or `unowned`?
- Confusion about where should put the [unowned self]
Trending Questions
- UIImageView Frame Doesn't Reflect Constraints
- Is it possible to use adb commands to click on a view by finding its ID?
- How to create a new web character symbol recognizable by html/javascript?
- Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
- Heap Gives Page Fault
- Connect ffmpeg to Visual Studio 2008
- Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
- How to avoid default initialization of objects in std::vector?
- second argument of the command line arguments in a format other than char** argv or char* argv[]
- How to improve efficiency of algorithm which generates next lexicographic permutation?
- Navigating to the another actvity app getting crash in android
- How to read the particular message format in android and store in sqlite database?
- Resetting inventory status after order is cancelled
- Efficiently compute powers of X in SSE/AVX
- Insert into an external database using ajax and php : POST 500 (Internal Server Error)
Popular Questions
- How do I undo the most recent local commits in Git?
- How can I remove a specific item from an array in JavaScript?
- How do I delete a Git branch locally and remotely?
- Find all files containing a specific text (string) on Linux?
- How do I revert a Git repository to a previous commit?
- How do I create an HTML button that acts like a link?
- How do I check out a remote Git branch?
- How do I force "git pull" to overwrite local files?
- How do I list all files of a directory?
- How to check whether a string contains a substring in JavaScript?
- How do I redirect to another webpage?
- How can I iterate over rows in a Pandas DataFrame?
- How do I convert a String to an int in Java?
- Does Python have a string 'contains' substring method?
- How do I check if a string contains a specific word?
Yes the singleton holds a strong reference to itself, and can't be disposed.
Base on that is safe to say that you can safely create weak or unowned references to it.
From Apple documents:
An easy way to test it is to test from the main class.
Between the first (disposed) class and the second (newly created) class there are no references to the singleton.