Sign in to follow this  
eshalev

Objective C @ for strings

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