开发者

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?

Actuall开发者_C百科y I’m not clear about the pointer concept (give a suitable link to clear it)


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".


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜