Object sent -autorelease too many times

I have this code that simply returns Date date as a string formatted:

+(NSString*) getTodayString_YYYY_MM_DD {

  NSDate    * today = [NSDate date];

  NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  [formatter setDateFormat:@"yyyy-MM-dd"]; 

  return [[formatter stringFromDate:today] autorelease];

}

With tools, I don't get a memory leak, but when I parse, Xcode says:

Object sent -autorelease too many times

If I understand correctly, I have to manually publish the formatter, because I create it using 'alloc', but I can not free it, because I need to return the value, so I add auto-advertising.

How can I improve this?

thank,

g.

+3
source share
2 answers

You are -autoReleasing NSString, not a formatter.

You do not need auto-recovery, since -stringFromDate: gives you an already automatically saved line.

, :

+(NSString*) getTodayString_YYYY_MM_DD {

  NSDate    * today = [NSDate date];

  NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  [formatter setDateFormat:@"yyyy-MM-dd"]; 

  NSString *retString = [formatter stringFromDate:today];
  [formatter release];

  return retString;

}
+8

, NSDate description YYYY-MM-DD HH:MM:SS ±HHMM:

+ (NSString *) getTodayString_YYYY_MM_DD
{
    return [[[NSDate date] description] substringToIndex:10];
}

. , , , NSDateFormatter.

0

Source: https://habr.com/ru/post/1745231/


All Articles