0

Possible Duplicate:
NSString retain Count

I am the beginner for iPhone programming. I am dealing with NSString. I got a doubt explained below.

@implementation Sample;

NSString *str;

-(void)viewDidLoad
{
    str = [[NSString alloc] initWithString:@"Hello"];

    // Why retain count is some random value? (Eg.2147234)
    NSLog(@"retain count of string %d",[str retainCount]);

    [str release];
}

-(void)printString
{
    // Why the value for "str" getting printed here,
    // though its released in viewDidLoad?
    NSLog(@"string is %@",str);
}
Community
  • 1
  • 1

2 Answers2

2
  1. Don't look at retainCount. It'll confuse you, and it doesn't help.

  2. Constant strings are built right into the code -- they're never allocated or released. It's fine for you to retain and release them as you would any other object, but don't expect a constant string to be deallocated at any point.

Caleb
  • 124,013
  • 19
  • 183
  • 272
0

In objective-c, an init method doesn't necessarily return the same object created using alloc. It may release self and then return another object.

In the case of initWithString there's a good chance it returns the @"Hello" constant string object, instead of initialising a new string, since it's faster and has no negative side effects (both strings are immutable).

As @Caleb said, normal memory management rules don't apply to constant strings. You can't release it, it will always be there.

But all of this is undocumented behaviour and subject to change. You can't depend on it, and the code you've posted is buggy, after releasing something you shouldn't ever try to access it.

Instead you should follow standard practices, which says you should always release an object and set any pointers to it to nil when you're done with it. If you had set str to nil after releasing it, you would be seeing the expected behaviour.

Or even better, just turn ARC on, and forget about all these things.

Abhi Beckert
  • 32,787
  • 12
  • 83
  • 110