Re: Autorelease Question
Re: Autorelease Question
- Subject: Re: Autorelease Question
- From: Adam Leonard <email@hidden>
- Date: Thu, 20 Nov 2008 22:55:33 -0500
See the Cocoa Fundamentals Guide:
"Class factory methods are implemented by a class as a convenience
for clients. They combine allocation and initialization in one step
and return the created object autoreleased. These methods are of the
form + (type)className... (where className excludes any prefix)."
"autoreleased" !
Someone correct me if I am wrong about this, but the statement that
convenience methods always return an autoreleased object is a
generalization that is implementation specific and not always true.
As far as I can tell, it is not true in the case of [NSString string]
on 10.5.
For example, try running this code:
NSString *string1 = [NSString string];
NSString *string2 = [[[NSString alloc]init]autorelease];
NSString *string3 = [NSString stringWithFormat:@"hello"];
NSString *string4 = [[[NSString
alloc]initWithFormat:@"hello"]autorelease];
NSLog(@"string1: %p, string2: %p, string3: %p, string4:
%p",string1,string2,string3,string4);
On my computer, string1 and string2 always point to the same address
and string3 and string4 point to different addresses.
Next, look at the retain counts of each. string1 and string2 return
INT_MAX, while string3 and string4 return 1.
And if you really want, try:
int i;
for(i=0; i<1000; i++)
[string1 release]; //no crash
for(i=0; i<1000; i++)
[string3 release]; //CRASH
All of this would leave me to believe that [NSString string] is NOT
"combining allocation and initialization in one step and returning the
created object autoreleased". Instead, it is likely implemented like
this:
+ (id)string
{
return @"";
}
(i.e., returning an empty constant NSString)
Again, this makes sense. Why waste memory by having more than one
empty string instance?
These are all implementation details, so I'm not suggesting that it is
ok to ignore the memory management rules , but it is also an
implementation detail as to when NSString decides to fulfill its end
of the memory management agreement.
Another case where a class factory method that does call autorelease
will not "return the created object autoreleased" is when its call to -
init.... returns nil
For instance, One example given, +dataWithBytes:length:, is documented
to return nil in cases when "the data object could not be created"
I think this is a bug in the documentation. I am curious to know what
others think.
Adam Leonard
_______________________________________________
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