Sign in to follow this  
eshalev

Objective C @ for strings

Recommended Posts

eshalev    100
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
eshalev    100
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
jpetrie    13159
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
bronxbomber92    275
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
daviangel    604
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
eshalev    100
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this