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.5k 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
- Navigate after logged in with webservice
- URLSession requesting JSON array from server not working
- When using onDrag in SwiftUI on Mac how can I detect when the dragged object has been released anywhere?
- Protect OpenAI key using Firebase function
- How to correct error: "Cannot convert value of type 'MyType.Type' to expected argument type 'Binding<MyType>'"?
- How to share metadata of an audio url file to a WhatsApp conversation with friends
- Using @Bindable with a Observable type in SwiftUI
- How to make a scroll view of 9 images in a forEach loop open on image 6 if image 6 is clicked on from a grid?
- Using MTLPixelFormat.rgba16Float results in random round-off errors
- Search and highlight text of current text in PDFKit Swift
- How is passing a function as a parameter related to escaping autoclosure?
- Actionable notification api call not working in background
- Custom layout occupies all horizontal space
- Is it possible to fix slow CKAsset loading on Cloudkit?
- Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value - MapView.isMyLocationEnabled
Related Questions in MEMORY-MANAGEMENT
- Polars with Rust: Out of Memory Error when Processing Large Dataset in Docker Using Streaming
- how is strncpy able to copy from source to empty destination?
- Mallocing int* inside of int** gives unexpected integer values in the first and sometimes second allocation
- How to prevent R from slowing down in long analysis besides freeing up memory?
- React Navigation: Navigate into page, increase RAM, navigate back and RAM stays high
- Java Memory UTF-16 Vs UTF-8
- How to protect a page so that it cannot be write in mips arch?
- How does pre-allocating a pool of SocketAsyncEventArgs objects upfront improve the performance of a server application in c#
- Finding total RAM consumption of process, including swap
- How do special libraries in C cause memory allocation to fail or interact improperly?
- Does CLR add overhead fields to type which value is null?
- How do I improve the performance of this C# code - looping through a DataTable and building a Dictionary?
- Numpy memmap still using RAM instead of disk while doing vector operation
- Does the Direct Memory Access (DMA) interfere with the execution of user program execution?
- How to read and process big csv file fast and keep memory usage low in java?
Related Questions in SINGLETON
- Laravel's Singleton issue (works in Tinker, not in the served app)
- Can out-of-order execution of CPU affect the order of new operator in C++?
- What should I use between object class and Hilt @Singleton class. in Android
- Android kotlin casting warning
- Is it possible for some singletons to outlive other singletons
- The singleton class has different assigned addresses
- JAVA - Implementing a serialisable and mutable Singleton
- Does the static initialization order fiasco happens with C++20 modules?
- EXC_BAD_ACCESS (SIGBUS) KERN_PROTECTION_FAILURE when calling Singleton's function inside a Timer's closure
- Swift: Singleton class "extends" from protocol
- Why do we need a constructor for a singleton?
- How to test a Singleton with Jest ? Comparison made between two syntaxes
- IllegalStateExeption Another SimpleCache Instance uses the folder after using single kotlin android
- What are the problems with creating a Singleton using an unnamed struct in C?
- Unity Player Prefs Not Updating After Building
Related Questions in REFERENCE-COUNTING
- How to check reference counting issues when doing direct manipulations of CPython objects?
- Direct access to the internal fields of a CPython object
- how to clone an Rc from a method that takes in &self
- Pytest/Mock keeping around extra object references in case of caught exceptions
- Is it possible to access a variable from the enclosing scope inside a callback function in Rust without reference counting or mutexes?
- IronPython garbage collection - How does it provides compatibility with C-extensions?
- Sharing objects implementing trait in Rust
- COM programming reference count, release and destroy
- Reference Counting Using RCObjects vs. static inline C++
- Reference count after deleting a literal
- How to count references in java correctly?
- How do I prevent an arbitrary object's destructor from ever running in Python?
- In Swift, what is the accurate way to check the reference count of an class object in memory?
- In Rust, how does Weak<T> know when the inner value has been dropped?
- Why do Python objects without circular references still get removed by garbage collection?
Related Questions in UNOWNED-REFERENCES
- Difference between unowned var something: Something! and weak var something: Something! in Swift
- Why weakifying a strong reference by using a local variable doesn't work?
- Swift Weak Reference Much Slower than Strong Reference
- Understanding weak and unowned reference in Swift under the hood
- Swift unowned self leaking when 'owned' by a view being presented
- How Unowned reference works with capture variables in Swift
- Does ARC hold a count for unowned reference?
- Swift - Capture List self clarification
- Swift - @escaping and capture list clarification
- Weak or Unowned or None
- Add [unowned self] to the closure argument Swift
- Confusion about where should put the [unowned self]
- When both properties can never be nil what difference does unowned make in terms of allocated memory?
- Why can't I give an unowned constant an initial value?
- Swift. unowned may only be applied to class and class-bound protocol types. weak works fine
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 # Hahtags
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.