开发者

String deallocs when given value from NSDateFormatter

The mysteries of Objective-C plague me yet again.

I have a string. It's defined in a header file called "Common.h".

If I开发者_如何学运维 give it a value thusly:

_DATESTRING = @"2011-08-16";

There is no problem, and it sticks around forever, however, if I do this:

_DATESTRING = [format stringFromDate:[NSDATE dateWithTimeIntervalSinceNow:0]];

I get a "message sent to deallocated instance" further down the pipes.

Why?


// This is a string that's not going to be released
_DATESTRING = @"2011-08-16";

// This is a string that's autoreleased
_DATESTRING = [format stringFromDate:[NSDATE dateWithTimeIntervalSinceNow:0]];

// You want somethhing like this
_DATESTRING = [[format stringFromDate:[NSDATE dateWithTimeIntervalSinceNow:0]] retain];

In short, if your method name contains alloc, copy, new or mutableCopy you have to release it yourself. Otherwise it's already autoreleased so if you want to keep it around you need to retain it.


Where exactly is down the pipes?

The method stringFromDate: returns an autorelease object, so I'm quite sure that it's getting automatically deallocated when you want to use it. It doesn't happens with string literals because these do not follow the standard memory management conventions for objects.

You may want to add a retain message:

_DATESTRING = [[format stringFromDate:
                             [NSDATE dateWithTimeIntervalSinceNow:0]] retain];


because -stringFromDate: returns autoreleased object. If you want it to stick around forever, you need to send -retain message to it, that is:

_DATESTRING = [[format stringFromDate:[NSDATE dateWithTimeIntervalSinceNow:0]] retain];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜