0

I am doing some work on reference count increase. Below is the sample.

.h file.

@property (nonatomic, retain) NSString *s1;

.m file

@synthesize s1;

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

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

    [s1 retain];
    NSLog(@"%d",[s1 retainCount]);

    [s1 copy];
    NSLog(@"%d",[s1 retainCount]);
}

When i am finding reference count, it is showing -1 for all of them, and i am bit confused for this, please help me.

Kashif
  • 1,137
  • 2
  • 20
  • 45
  • NEVER use `retainCount`- http://stackoverflow.com/questions/4636146/when-to-use-retaincount/4636477#4636477 – Volker Mar 31 '14 at 08:17
  • Just to emphasize: Never use retainCount. And do yourself a favour and start using ARC. – gnasher729 Mar 31 '14 at 08:24
  • possible duplicate of [RetainCount is -1 after alloc?](http://stackoverflow.com/questions/16728133/retaincount-is-1-after-alloc) – Martin R Mar 31 '14 at 08:25

1 Answers1

3

It prints -1 because you're using the wrong string format.

Since retainCount returns a NSUIngeter (i.e. and unsigned integer), you should use

NSLog(@"%lu", (unsigned long)myNSUInteger); 

Other than that, it's worth remarking that you should never rely on retainCount.

See When To You Retain Count.

Also, from the official documentation:

This method is of no value in debugging memory management issues. Because any number of framework objects may have retained an object in order to hold references to it, while at the same time autorelease pools may be holding any number of deferred releases on an object, it is very unlikely that you can get useful information from this method.

Gabriele Petronella
  • 102,227
  • 20
  • 204
  • 227