I have Util class as follows.
@implementation Util
- (NSString*) getTodayString
{
NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// display in 12HR/24HR (i.e. 11:25PM or 23:25) format according to User Settings
[dateFormatter setDateFormat:@"YYYY/MM/dd"];
NSString *now = [dateFormatter stringFromDate:today];
[dateFormatter release]; ///???
[today release]; //???
return now;
}
@end
And I use the class
- (void)awakeFromNib
{
Util *ut = [[Util alloc] init];
NSString* now = [ut getTodayString];
NSLog(@"User's current time in their preference format:%@",now);
[currentTime setObjectValue:now];
[now release]; ///???
[ut release];
}
I’m confused when releasing objects.
In getTodayString ::
Q1. [dataFormatter release] is necessary?
Q2. [today release] is necessary?
I guess I don’t need to release them as I didn’t alloc myself. If that’s true, when those objects are released?
In awakeFromNib ::
Q3. [ut release] is necessary?
Q4. [now release] is necessary?
I guess I have to release ut as I create the object explicitly, but not suer about now object.
- How one can determine when is the object is released?
- With python/C#/Java one doesn’t care about this kind of deallocation of memory anymore. Is it also OK with Objective-C if I don’t care about them?
dataFormatter: yes, you alloc/init’d it.
today: no, it was returned autoreleased from a factory method.
The same,
ut: yes, you alloc/init’d it.
now: no, it was returned autoreleased from a factory method.
it’s released when
releaseis called on it, ifautoreleaseis called,releasewill be called during the next run of the Autorelease Pool.No, it’s not ok. If you do not clean up after yourself you will have substantial memory leaks, in the iOS environment that means a quite shutdown of your app. In a Mac app that can lead to eating up a ton of memory and not being a good citizen. This is assuming a non garbage collection environment. Ie most.
I’m guessing the heart of your question is you aren’t sure when you are responsible for calling
releaseand when you get anautoreleasedobject (or rather, when you are responsible for calling release on the object). It’s by convention. If you call any method that returns an object that does not contain the words: init/copy then it is not your responsibility to call release. If you retain, you release (There may be some more rules to follow, but that’s the first one to really start understanding this, in my opinion). If you ever call alloc/init/copy, then you must callreleaseat some point.A GREAT teacher is Build & Analyze in Xcode. This will quickly point out where you screwed up and really help to understand what is going on.