Re: Autorelease question
Re: Autorelease question
- Subject: Re: Autorelease question
- From: "Sherm Pendley" <email@hidden>
- Date: Fri, 4 Apr 2008 06:31:47 -0400
On Thu, Apr 3, 2008 at 10:18 PM, Dmitry Markman <email@hidden> wrote:
>
> On Apr 3, 2008, at 9:52 PM, Chris Suter wrote:
>
> You're releasing things you shouldn't be. Take some time to read the
> > memory management documentation.
> >
>
> well, exactly
>
> so here is what I have
>
> NSString *nsFontName = [NSString stringWithCString:fontName
> encoding:NSMacOSRomanStringEncoding];
> NSString *textString = [NSString stringWithCString:"Hello From
> Cocoa" encoding:NSMacOSRomanStringEncoding];
> NSGraphicsContext *context = [NSGraphicsContext
> graphicsContextWithGraphicsPort:cgContext flipped:TRUE];
> NSColor *cocoaColor = [NSColor colorWithCalibratedRed:r green:g
> blue:b alpha:alpha];
> NSFont *font = [NSFont fontWithName:nsFontName size:fontSize];
> NSMutableDictionary *stringAttributes = [NSMutableDictionary
> dictionaryWithCapacity:4];
>
> documentation
... hold on there. Now, normally I'm the last guy in the world to discourage
reading the docs. :-) But in this case, the memory-management guidelines
refer to the names of the methods you're using, not their descriptions in
the docs. So, the methods you're calling are:
+stringWithCString:encoding:
+graphicsContextWithGraphicsPort:flipped:
+colorWithCalibratedRed:green:blue:alpha:
+fontWithName:size:
+dictionaryWithCapacity:
None of those method names begin with +alloc or +new, or contain the word
"copy". So you don't need to release them; in fact, you must not do so. And
once you learn that simple pattern of method names, you'll know that for any
object you get back from any method, without having to look it up. The
answer is already right there in the method name itself.
Now, some of these are probably returning autoreleased objects, like
+dictionaryWithCapacity:. The font manager probably caches recently-used
font objects, and returns references to them from +fontWithName:size:.
Colors might refer to palette entries in some graphics modes. But you don't
need to be concerned with those details when writing your own code. The key
point here is that, for whatever reason, it's not your responsibility to
release the returned object. And, the fact that it's not your responsibility
to do so can be inferred from the name of the method itself, without
resorting to documentation.
As you've noted, you can sometimes get away with releasing something when
you're not supposed to. That's the nature of the beast - not guaranteed to
work doesn't mean guaranteed to not work, if you follow me.
sherm--
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden