Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSObject released, NSString, NSArray not?

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?

like image 817
user1559227 Avatar asked May 09 '13 09:05

user1559227


1 Answers

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.

like image 64
Sulthan Avatar answered Oct 05 '22 01:10

Sulthan