0

I noticed that after updating my Xcode to 4.2 retainCount is always equals to -1. I don't use ARC in my project and I even tried to create new projects and switched ARC option to off in project settings but next lines works really strange:

NSString *string = [[NSString alloc] init];
NSLog(@"%i", [string retainCount]);   //-1
[string retain];
[string retain];
[string retain];
NSLog(@"%i", [string retainCount]);   //still -1
[string release];
[string release];
[string release];
NSLog(@"%i", [string retainCount]);   //still -1

Am I miss something? I thought that if ARC option is turned off the project will work exact as before..

Philipp Schlösser
  • 5,179
  • 2
  • 38
  • 52
gN0Me
  • 437
  • 1
  • 6
  • 17
  • What about %d? `NSLog(@"%d, [string retainCount]);` – beryllium Nov 02 '11 at 20:42
  • 3
    Regardless of what happened, it's not a useful method and there really isn't a reason to use it. – FeifanZ Nov 02 '11 at 20:44
  • 1
    @beryllium - No, `-retainCount` returns an NSUInteger. Trying to format it as a floating point number should lead to compiler errors under LLVM, and garbage results otherwise. In any case, this is just [another reason not to use `-retainCount`](http://stackoverflow.com/questions/4636146/when-to-use-retaincount/4636477#4636477). I'm glad ARC turns it into a compiler error. – Brad Larson Nov 03 '11 at 16:53
  • I just wanted to play a bit with blocks and Block_copy to see how retain/release work with them. I tried to switch the compiler to GCC but still got -1 even when I use %d in NSLog – gN0Me Nov 04 '11 at 10:55

1 Answers1

6

First, let me preface this by saying that if you're calling retainCount, you're probably doing something wrong. This method should be only used by people writing low-level framework code, and even then only when debugging. Objects may get retained and autoreleased behind your back such that calling -retainCount is very misleading.

Anyway, I suspect that the answer is that [[NSString alloc] init] is returning a singleton object. It's immutable, and empty, so there's really no reason why it should create a brand new string for you when it can just return @"".

Lily Ballard
  • 182,031
  • 33
  • 381
  • 347
  • 2
    The explanation is correct, but I disagree on retainCount: it should never be called at all. It should have been removed a long time ago. – Sven Nov 02 '11 at 20:56
  • @SvenWeidauer: Unless you work at Apple, you're probably not writing low-level framework code. – Lily Ballard Nov 02 '11 at 21:12
  • I agree with you guys, I've never used retainCount in my products but I'd like to see how memory management works with blocks – gN0Me Nov 04 '11 at 10:56