views:

272

answers:

3

I'm just starting out with iphone development and ran across some example code that used @"somestring"

someLabel.txt = @"string of text";

Why does the string need the '@'? I'm guessing it's some kind of shortcut for creating an object?

+12  A: 

It creates an NSString object with that string as opposed to the standard c char* that would be created without the '@'

cobbal
The string is created at compile time. The GCC Objective-C compiler must use a class with a specific ivar layout. It can be overridden with -fconstant-string-class flag.
dreamlax
+7  A: 

In Objective-C, the syntax @"foo" is an immutable, literal instance of NSString.

Robert Harvey
A: 

Just an interesting side note... NSString literals created by using the @"..." notation are not autoreleased. They essentially just hang around until your program terminates.

Just a caution that if you want to maintain control over whether or not this object gets released (freed) down the road you may want to consider using something like:

[NSString stringWithString:@"..."];

...instead. This would create an autoreleased version of the same string that will be freed from memory next time the "autorelease pool is drained".

Just food for thought.

Cheers-

J.Biard
They "hang around" because they are static objects created by the compiler.
dreamlax
This is fairly silly. @"..." strings are allocated at compile time and stay around for the entire duration of the application. So no further memory is used no matter how long they are used for, and no memory is ever released no matter how few or many times they are used.Your suggestion would potentially allocate a new object and push it on to the autorelease stack which could never improve memory usage.Thankfully, NSString is almost certainly optimized to do nothing in this case, which just makes this entire stringWithString statement pointless.
Peter N Lewis
Thanks for the clarification. I guess my intention is to say that when using @"..." your application is always going to consume that memory even if you never use the object; because as you say these objects are created by the compiler. This is probably not an issue 99.9% of the time but if you have a large number of such strings in your program the effects become more important.
J.Biard