If I write -
NSObject *a = [[NSObject alloc] init]; // or UIView or something
[a release];
NSLog(@"a = %@", a); // causes EXC_BAD_ACCESS, fine
But, if I write -
NSArray *a = [[NSArray alloc] init]; // or NSString or NSDictionary
[a release];
NSLog(@"a = %@", a); // no crash, prints empty array or string
Why second case doesn't cause bad access, since it's released?
Accessing a released object doesn't have to make the application crash immediately.
Note than even if you release the object, the memory stays there for some time, with the same contents. You will get a crash only if the object memory has already been overwritten by some other object. And note that even with overwritten memory you don't have to get a crash. You can get only some very strange behavior (e.g. when the object is a NSString
, it can get different contents).
Basically, this behavior is totally random. Using a released object can make your application crash immediately or in 5 minutes or in 2 hours.
Edit:
Thanks to Martin R for an interesting comment. It seems that an array created by [[NSArray alloc] init]
, that is, empty immutable array, returns always the same instance. That means your release
won't make it to be deallocated. However, this behavior can easily change, can differ between compilers or OS versions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With