Re: NSString initWithFormat and stringWith
Re: NSString initWithFormat and stringWith
- Subject: Re: NSString initWithFormat and stringWith
- From: Dave DeLong <email@hidden>
- Date: Wed, 27 May 2009 08:41:13 -0600
Hi Ignacio,
I just ran a simple test, pasted below:
NSString * one = [NSString stringWithString:@"Hello"];
NSString * two = [[NSString alloc] initWithString:@"Hello"];
NSLog(@"%X, %X, %X", one, two, @"Hello");
What you see logged is that the three strings point to the same
address in memory. From this we can conclude that the compiler is
optimizing this code, like so: It sees that you're creating a non-
mutable object from a non-mutable object, and so it replaces them all
with THE SAME OBJECT. In this particular case, it's an instance of
NSConstantString (a private subclass of NSString). ConstantStrings
are singletons by default (hence "constant"), and so their retain
count is hard-coded to something like NSUIntegerMax so that they
cannot technically be released. This, however, does not excuse you
from following the rules of proper memory management.
As others have said, retainCounts are generally non-useful pieces of
information.
HTH,
Dave
On May 27, 2009, at 7:59 AM, Ignacio Enriquez wrote:
Hi.
I have a basic question regarding Class methods and instance methods
and memory allocation. (this is in iPhone OS 3.0 beta 5)
1.- What is the difference between string1 and string2? where
NSString *string1 = [NSString stringWithFormat:@"myFirstString"];
NSString *string2 = [[NSString alloc]
initWithFormat:@"mySecondString"];
I thought that string1's memory allocation and release would be done
by the system (autoreleased) and string2's memory and release should
be done by me (by [string2 release])
Am i mistaking?
A funny thing is when doing:
NSLog(@"retainCount %i %i", [string1 retainCoung], [string2
retainCount]);
I got :
"retainCount 2147483647 2147483647"
So It seems that both objects are autorelease objects... Why is that?
I thougth that string2 retainCount would be 1.
2.- How can I get two simple NSString instances with a retainCount
equal to 1
Any response would be very appreciated.
Regards
Ignacio
_____________________________________________
_______________________________________________
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
_______________________________________________
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