Re: Need to release "constant objects"?
Re: Need to release "constant objects"?
- Subject: Re: Need to release "constant objects"?
- From: Eric Wang <email@hidden>
- Date: Sat, 08 May 2004 03:31:25 -0400
on 5/4/04 7:48 PM, Jerry Krinock at email@hidden wrote:
>
I use these things I call "constant objects", mostly strings, that I assign
>
to other variables, as needed, in a particular class. So, I declare them as
>
globals at the top of the file like this (I show NSNumbers instead of
>
NSStrings as examples because the shorter lines fit better in email):
>
>
static NSNumber* objectTrue;
>
static NSNumber* objectFalse;
>
>
then I create them in my class's -init method:
>
>
objectTrue = [[NSNumber alloc] initWithBool:TRUE] ;
>
objectFalse = [[NSNumber alloc] initWithBool:FALSE] ;
>
>
and then I just assign to other variables whenever needed.
>
>
I never bother to release them, because I need them as long as the program
>
is running. I was wondering, however, when I run "leaks" from the command
>
line, do these show up as leaks and, if so, is there a better idiom? I like
>
to see no warnings and no leaks.
>
>
Jerry Krinock
>
San Jose CA USA
Jerry,
You do not need to release constant objects if they are to remain available
for the lifetime of the application. The memory used by the constant objects
will reclaimed by the OS when the application terminates.
You probably shouldn't be initializing your constants in the class' -init
method. Your constant initialization methods will be called unnecessarily
each time you create a new instance of the class. Instead, do your constant
initialization in the +initialize class method, which works like a static
initializer in Java. It will be called only once, when the class is loaded.
Unfortunately, this practice is nowhere to be found in Apple's developer
documentation. I only discovered it after reading through someone else's
source code. I really wish someone (perhaps Apple?) would come out with a
Cocoa Best Practices book that documented tips and tricks, what works and
what doesn't, and the rationale for doing something a certain way in Cocoa.
The kind of stuff you can't find in the API docs, but only from mailing
lists, source code, and through experience. Having worked in the Java world,
I find this is something that is sorely lacking in the Cocoa community.
As a sidenote, Objective-C programmers typically use YES and NO, instead of
TRUE and FALSE for their boolean variables.
Eric Wang
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.