NSDateFormatter causing zombie woes
I've always had some issues getting the infamously picky NSDateFormatter from causing memory instability in my code. I must not grasp how to use it properly. I've looked at tons of sample code and modeled my method after this, but it seems memory issues still plague me. The issues I'm开发者_StackOverflow having is that this method is creating a zombie - not too sure how / why. Some insight would be wonderful!!
-(NSString *)getTimeZoneFormatedDate:(int)subtractMinutes TimeZoneOffset:(NSString *)timeZoneOffset
{
float timeZoneOffsetInt = [timeZoneOffset floatValue];
//Calculate the requested UTC time
NSDate *UTCDateTimeNow = [NSDate date];
NSDate *UTCDateTimePast = [UTCDateTimeNow dateByAddingTimeInterval:((subtractMinutes*60)+(timeZoneOffsetInt*60*60))];
//Round the minutes down
NSDateComponents *time = [[NSCalendar currentCalendar]
components:NSHourCalendarUnit | NSMinuteCalendarUnit
fromDate:UTCDateTimePast];
int minutes = [time minute];
float minuteUnit = floorf((float) minutes / 10);
minutes = minuteUnit * 10;
//Format the minutes string
NSString *minuteString;
minuteString = [NSString stringWithFormat:@"%d",minutes];
if ([minuteString length] < 2)
minuteString = [@"0" stringByAppendingString:minuteString];
//Format the rest of the date & time
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
NSDateFormatter *dateFormatter;
dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setTimeZone:timeZone];
[dateFormatter setDateFormat:@"yyyy-MM-dd, HH:"];
NSString *yearMonthDayHourString = [dateFormatter stringFromDate:UTCDateTimePast];
//Put the two together and return it!
return [yearMonthDayHourString stringByAppendingString:minuteString];
}
I'm implementing it like so:
NSString *timeZoneText = [self getTimeZoneFormatedDate:minuteModifier*-10 TimeZoneOffset:radarTimeZoneOffset];
If I run my project with the dateformatter commented out and my method just returning:
return @"blah blah";
No issues - everything runs bug free. So, I believe it's safe to assume the issue lies within! Thanks for the help!
I think the problem is that your "NSString *yearMonthDayHourString" is autoreleased string. You can retain it in your implementation code something like that
self.timeZoneText = blabla if timeZoneText is property with retain or just [timeZoneText retain]; and release later;
You can try out NSDateFormatter's getObjectValue:forString:range:error: method. Maybe returned NSError provides you a reasonable explanation why it failed.
On the other hand there might be an easier way to get the result:
NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"dd-MMM-yyyy HH:mm:ss"];
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[dateFormatter setLocale:usLocale];
[usLocale release];
return [dateFormatter stringFromDate:date];
精彩评论