I created a new project, enabled Zombie Objects (Edit Scheme -> Diagnostics). I initialized two objects: ZombieTest and ZombieTest2(inherit from NSObject). After running the app, I opened debug memory graph and only the object that inherit from NSObject appears as NSZombie.
Why does object become NSZombie only when inherit from NSObject?
691 Views Asked by Hen Shabat At
2
There are 2 best solutions below
0
Rob Napier
On
Conversion to NSZombie is handled by the ObjC runtime, and requires an ISA swizzle (i.e. the class of the object is changed at runtime). Pure Swift classes don't support that.
There are cases where a pure Swift object might still become an NSZombie, since pure Swift objects are sometimes bridged to the ObjC runtime, but those are implementation details that can't be relied on.
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 XCODE
- I am getting lots of errors when building react native app in Xcode
- Xcode commits (possibly outside of any branch) disappeared, how to get them back?
- Can't run built SFML project from Xcode template
- Postal Framework crash in iPhone but runs successfully in simulator
- React Native - RealmJS - Linker command failed with exit code 1
- how to install xcode on macos hight sierra without apple account
- Xcode: Can't Attach to process
- Issue with Xcode Target and settings for Apple Watch App
- There are no active runners online GitLab
- My project code not running in Xcode(15.3) but the same code running in Xcode 14.2 in swift how to fix in xcode 15.3?
- How to press and hold in Xcode simulator
- Memory management for image data storing and retrieving with SwiftData (or CoreData)
- Error: spawn flutter ENOENT in flutter build_runner
- Can a project using Crashlytics have a GoogleService-Info.plist file renamed to something else?
- What changed from xcode 13.2.1 to 14.2 that would affect an app's entitlements?
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 NSOBJECT
- How can I implement struct to inherit a protocol with <NSObject>
- What do these Xcode warnings mean?
- system.FormatException: 'Input string was not in a correct format.' in IAppversion class. Conversion from NSObject to string
- Swift: Access struct/class variables by string name
- How to unarchive MLMultiArray with NSKeyedUnarchiver?
- Xamarin.IOS / c# - Get NSObject values
- Is it possible to save a value to CoreData using key path?
- Collectionview in NSObject Class doesn't work?
- Why can't I mutate an NSObject allocated as mutable, referenced as immutable, then cast back to mutable?
- Setting Observer for Swift Objects/Properties
- Xcode code completion suggests `printContent(_)` above `print(_)`
- Xcode 13 ('Product' is ambiguous)
- Core Data NSObject to Int
- Swift defined convenience init is not accessible in objective-c
- Is there a way to assign a variable of Swift enum type to a variable of NSObject type?
Related Questions in NSZOMBIE
- How can I Intentionally create a Zombie Object in Swift
- iOS 14 crash zombie when use dispatch_semaphore
- ~500 NSZombie warnings on Xcode memory graph from iOS 13 application
- Why does object become NSZombie only when inherit from NSObject?
- Why dose the NSString become NSZomie in this code?
- Why NSInvocation return value creates a zombie?
- In what situation will a NSZombie be created in an ARC environment?
- Crashing MapKit
- How can I demonstrate a zombie object in Swift?
- Enabling Zombie Objects causing memory pressure crashing
- Over release a object in an dictionary that cause EXC_BAD_ACCESS error?
- THREAD 1: EXC_BREAKPOINT CALayer removeAllAnimations message sent to deallocated
- iOS Swift EXC_BAD_ACCESS code 2 SearchTextField (UITextField subclass)
- EXC_BAD_ACCESS when closing NSDocument window (ARC enabled)
- EXC_BAD_ACCESS on long press; no zombie activity
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?

tl;dr: because
NSZombiesare implemented to only affectNSObjectand its subclasses. (This doesn't have to do with Swift, either: Obj-C objects which aren't subclasses ofNSObjectalso won't become zombies.)Upon initialization (
__CFInitialize, called when the framework is loaded), the CoreFoundation framework sets up a lot low-level Foundation and CoreFoundation behaviors; among other things, it looks for theNSZombieEnabledenvironment variable, and if present, enables zombies by calling the__CFZombifyNSObjectfunction:When zombies are enabled,
__CFZombifyNSObjectreplaces the implementation of-[NSObject dealloc]with a different implementation (__dealloc_zombie):This means that all subclasses of
NSObjectand their descendants, upon deallocation, will call through to__dealloc_zombie. So what does__dealloc_zombiedo?In more human-readable terms, it:
[self class]_NSZombie_<our class name>, it creates one by duplicating the_NSZombie_class and gives the duplicate a new name (this creates a copy of the class with all of its method implementations, or lack thereof)self, and replaces its class with the new class, so that if you message it in the future, you dispatch to_NSZombie_<whatever>_NSZombie_is a class which implements no methods, so sending it any message (method call) ends up falling into a code path in message forwarding which prints out the "message sent to deallocated instance" message.Effectively, this method of implementing zombies hinges on inheritance from
NSObject(because allNSObjectsubclasses should call[super dealloc]on deallocation, eventually reaching[NSObject dealloc]); things which don't inherit fromNSObjectdon't inherit this implementation. (You can also actually see this by implementing anNSObjectsubclass which doesn't call[super dealloc]in its-deallocimplementation — the object won't get zombified on release.)Do
NSZombieshave to be implemented this way? No, it's certainly possible to imagine other schemes which would allow pure Swift objects to participate (Swift runtime initialization could also look up theNSZombieEnabledenvironment variable and do something similar), but there's somewhat less of a benefit to putting in the effort. As Rob mentions in his answer, this works largely because we're able to swizzle out the class of the deallocated instance (this is actually possible with the Swift runtime, but not exposed externally), but crucially, even if we did this, it wouldn't help cases of static method dispatch, which is possible on object types in Swift (e.g. forfinalclasses). [Alexander alludes to this in his comment.]So, largely, it's really easy to implement this way for Obj-C, and there are somewhat limited benefits for taking the time to do this for pure Swift classes too.