I'm just learning ObjectiveC....
And for last two days I can not find any explanation why this code gives always a retainCount of -1 (negative value)... in all cases !!!
NSString *test1 = @"Test string";
NSLog(@"test1 retain count is: %d", [test1 retainCount]);
[test1 retain];
NSLog(@"test1 retain count is: %d", [test1 retainCount]);
[test1 release];
NSLog(@"test1 retain count is: %d", [test1 retainCount]);
I also found out that most people get 2147483647 instead of -1 .... But nevertheless even in your case the retaincount stays the same ... What machine do you have and what version of xcode ?
When you declare NSStrings like that you don't need to release them.
Quote:
Does the NSString returned by @"" need to be released, or is it autoreleased?
Neither. @""-strings are of class NSConstantString?, and thus act like atoms in lisp; they hang around. That is, if you use @"cow" in two separate places in your code, they will be referencing the very same object.
I don't think -release or -autorelease does anything to either of them.
Over-releasing one might be bad. You should essentially treat constant strings as if they were autoreleased objects, and balance retains/releases appropriately.
Storage-wise, I think it makes sense to think of @"" literals the same way as "" literals: they are in memory the entirety of your program's lifespan. And that's the way it should be. If you "released" a string constant, the next time the code that uses that literal gets called, the object wouldn't be there anymore! You wouldn't "release" an integer constant, or a float constant, for example, if you had some function "int f(int x) { return x+1; }", it wouldn't make any sense to "free" the "1" part of the code! It's part of your program image! A string literal really isn't any different. Of course since NSString is an NSObject you can call retain on it, but I like to think of that as only making the API consistent with other NSStrings? which may be allocated dynamically.