bqbqhaha asks:
Let me ask you something as below.
- A variable declared as IBOutlet could be released?
- A variable declared as IBOutlet should be released?
I search for this issue many times, but still the answer is not found.
plz help me , plz
He is asking a question that most of us have when beginning with Interface Builder and Outlets. In plain English his question is “Should I release instance variables declared as IBOutlet?”
I personally believe that it is good coding practise to always match a retain with a release. The OS is somewhat lenient because if you quit your app all it’s memory is released anyway, so you sometimes get a away with just allocating something once and never releasing it.
This is also the reason why you never see the OS get into dealloc on quit. It only bothers with dealloc if your app is not already quitting. For example if you alloc and dealloc objects during the lifetime of your app.
There are two ways that an outlet can be set up. One is to simply add the keyword IBOutlet to the instance variables.
@interface ASiSTAppDelegate : NSObject { IBOutlet UIWindow *window; IBOutlet UINavigationController *navigationController; } |
The second method, which you would use if you want to access those members from outside of this class, is to attach IBOutlet to the matching properties.
@interface ASiSTAppDelegate : NSObject { UIWindow *window; UINavigationController *navigationController; } @property (nonatomic, retain) IBOutlet UIWindow *window; @property (nonatomic, retain) IBOutlet UINavigationController *navigationController; |
Both achieve the same goal of getting the memory address assigned to them when a XIB file is loaded and all contained class instances get unarchived. But note the retain in the brackets next to the property keyword. This causes the objects to be retained. In the first example they won’t be.
For properties that are defined as (retain) you have to have a release in the the dealloc method as well, even if they are outlets. This is because assigning them (and loading a XIB does these assignments) causes them to be retained due to exactly this keyword. But this again is only of consequence if you load the XIB, destroy the view, load the XIB again and so forth. Without the release the sub-objects in the Xib would not be released because they still have a retain count > 0. Which would leak memory.
For most apps you only load a XIB once and it is destroyed together with the rest of your app memory on quit . But if your app gets larger you might start to optimize and unload views that you don’t currently use from memory. This is the time when you also have to have the correct release statements in place.
If you are taking only one thing away from this article: Always match retains and releases.
Categories: Q&A