• Advertisement
Sign in to follow this  

Objective C @ for strings

This topic is 2879 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello, I have been developing with C and C++ for some time, and have recently started learning objective C. Can someone explain the role of the @ operator when dealing with strings: string=@"some text";

Share this post


Link to post
Share on other sites
Advertisement
I understand the optimization possible through using @, but... is there any case in which I would not use the @ operator?

Something like:
string="hello";
?

Share this post


Link to post
Share on other sites
Quote:

string="hello";

In Objective-C, an @-string is a immutable NSString instance. A string without the @ is a regular, C style string. They're not directly assignable, so your example won't even work. You'd need to initialize 'string' something like this:

NSString* string = [NSString initWithCString:"hello" ...]

Share this post


Link to post
Share on other sites
jpetrie explanation is totally correct, but just so you don't get caught up with the line of code he provided..

NSString* string = [[NSString alloc] initWithCString: "hello" encoding: NSASCIIStringEncoding];


Though, more than likely, you'll want to be working with UTF8 encoding, for which Apple has created a specific method for (though you can use the above and change the encoding parameter):
NSString* string = [[NSString alloc] initWithUTF8String: "hello"];

Share this post


Link to post
Share on other sites
Different types


@"hello" //this is an immutable NSString
"hello" //this is a const char *



-me

Share this post


Link to post
Share on other sites
I guess you haven't seen a EXC_BAD_ACCESS crash yet?
You'll see one of those during runtime if you pass a C style string to something that expects a NSString.

Share this post


Link to post
Share on other sites
I understand the explanation, but I still see a small difference:

I can not release: string=@"some text";

but I do need to release:
NSString* string = [NSString initWithCString:"hello" ...]

How does '@' effect memory allocation?

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement