Ranjeet Sajwan
Ranjeet Sajwan

Reputation: 1921

Object release behavior in iPhone

If I release mainPath in following example the program gives an error (because I’m releasing an object with zero counter)

NSString  *mainPath = [NSString stringWithFormat:@"%@/Documents/downloadFile.plist",NSHomeDirectory()];
NSLog(@"address is = %@",mainPath);
[mainPath release]; //Program failed here

But the following code works fine.

NSString *aa=@"hiiiii";
[aa release];

Can anyone explain this?

Actually I’m not clear about the pointer concept (give a suitable link to clear it)

Upvotes: 0

Views: 72

Answers (4)

JeremyP
JeremyP

Reputation: 86651

Constant NSStrings are a special case. They are allocated statically at compile time and can't be deallocated. You can send release to a constant string as many times as you like, it'll never get deallocated. This is achieved in the current implementation by setting the retain count to INT_MAX which is treated as a special value meaning "don't decrement me on release".

Upvotes: 3

zoul
zoul

Reputation: 104065

You should read the Cocoa Memory Management Guide or at least the Objective-C Tutorial by Scott Stevenson. (Really. Do it, you’ll save a lot of time in the long run.) The difference is that the first string is autoreleased, you do not own it and should not release it. The second string is special, I think it’s not allocated on the heap at all and the release is essentially a no-op here.

Upvotes: 3

Rog
Rog

Reputation: 18670

String with format is a convenience method that autoreleases the string so in this case you are likely to be sending a release message to an already deallocated object.

In your second example, you are creating the string statically so retain counts don't apply.

Upvotes: 2

grahamparks
grahamparks

Reputation: 16296

You don't need to release your objects in either of those cases.

As a rule of thumb, if you didn't use init (or initWithFoo:) to create the object, and didn't deliberately use retain to retain the object (plus couple of other rarer cases), you don't need to use release.

Upvotes: 0

Related Questions