Calling Methods On Released Objects
I think there is something I'm missing about memory management. Here's the code:
NSString *string = @"foo";
[string release];
NSLog(@"%@", string);
I expect to get a mem开发者_Go百科ory error with that code, but instead the code is ran without errors. I noticed this as I was following a book and a scrollView was released before setting properties and adding a subView (but after being inserted in the main view).
My question is, when are objects really deallocated? Would this e considered good coding style?
This works because your string
variable is pointing to a constant string that has been compiled into your application. retain
ing it does nothing and release
ing it does nothing as well. It exists in static memory, and it will only be destroyed when your program is unloaded from memory.
If you alloc, retain or copy an object, it is your responsibility to release it. Everything else is dealt with by the system and will be flushed with the auto release pool.
There are way too many memory management questions on SO already, have a quick look around to get yourself acquainted https://stackoverflow.com/search?q=memory+management+iphone
[edit] Probably the most important part of your question that you need to understand is in your second last paragraph:
I was following a book and a scrollView was released before setting properties and adding a subView (but after being inserted in the main view).
I haven't seen this code but it is likely that you added the scrollView to your UIView instance. In these cases, the receiving view always retain its subview(s) so you are free to release it.
Once the UIView instance is released it wil also send a release message to all its subviews, which includes the scrollView.
Makes sense?
Sending a message to a deallocated object is undefined behavior. You might get a memory error, you might end up sending a message to another object, you might end up sending an message to a phantom version of the former object — it all depends on implementation details and details of the environment at runtime that are mostly out of your control. In this specific case, you're running into the implementation detail that NSString constants are immortal.
As for specifically when an object will be deallocated, that's also an implementation detail. If you don't own an object and don't have a reasonable guarantee that it will still be around (e.g. you just got it by doing [someArrayYouOwn objectAtIndex:0]
), you should not be dealing with it.
The best policy: Just don't send messages to objects you no longer own. Follow the memory management rules.
精彩评论