-3
NSObject * obj1 = [[NSObject alloc] init];
NSLog(@"%d", [obj1 retainCount]);

NSString * string1 = [[NSString alloc] init];
NSLog(@"%d", [string1 retainCount]);

Can you guess the result ? Oh my god, it is "1 -1" ! That strange !

DungProton
  • 229
  • 3
  • 7

2 Answers2

1

First off... when should you use retain count?

Never use retainCount

Secondly...

No it's not strange since you are looking at a string literal that will never be released.

Community
  • 1
  • 1
David Rönnqvist
  • 56,267
  • 18
  • 167
  • 205
  • 1) You sure "a string literal that will never be released"? 2) In this case, I alloc-init, not release but retainCount was still -1 ! – DungProton Apr 08 '13 at 13:17
  • 1
    1) Yes, I'm sure. Look at _all_ the other questions asking about NSString and releasing or retain count. 2) That is because it is _always_ the same value. Again **stop looking at the retain count!** – David Rönnqvist Apr 08 '13 at 13:20
-1

The important point here is that any string you alloc and init that form will return the same object. It is the same as creating a NSNull. An empty string is a constant and will be always the same object.

Try this:

NSString * string1 = [[NSString alloc] init] ;
NSLog(@"%d %u", [string1 retainCount], string1);

NSString * string2 = [[NSString alloc] init];
NSLog(@"%d %u", [string2 retainCount], string2);

NSNull * theNULL = [NSNull null];
NSLog(@"%d %u", [theNULL retainCount], theNULL);

NSNull * theNULL2 = [[NSNull alloc] init];
NSLog(@"%d %u", [theNULL2 retainCount], theNULL2);

string1 and string2 are the same value, so both point to the null string. The same for both NSNull.

This kind of behavior explains why every init method begins with self=[super init], because a init can change self in cases like the null string or the NULL object.

Gabriel
  • 3,319
  • 1
  • 16
  • 21