Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Objective-C Basics (Retired) Foundation Framework NSArray

Why do we keep using "@"??

I am confused at the rate of using "@". It is being used everywhere. I am just not able to understand its usage ??

4 Answers

Stone Preston
Stone Preston
42,016 Points

you use @ when creating literal objects. Most of the time you will see it being used to create strings though it can be used to create arrays, numbers, and dictionary's as well. its much faster than having to allocate and init that object first.

so

@"some string"

is an NSString literal

@[@"a", @"b", @"c" ]

is an NSArray literal

and

@34

is an NSNumber literal

Thanks Stone.. We also use @ in NSLog. We are just printing the values so why do we create an object there?

Stone Preston
Stone Preston
42,016 Points

in and NSLog statement, the %@ inside the string to be logged to the console is a format specifier used for printing the value of objects to the console just like %d, and %f print ints and floats.

so @"this is a string is a string literal whereas NSLog(@"Im logging an object to the console: %@") is a format specifier INSIDE a string literal

So format specifier "%@" requires memory allocation and we are doing that using "@". Is my understanding correct?

Stone Preston
Stone Preston
42,016 Points

no, the format specifier is just a placeholder in the string thats used for formatting purposes. the value of the object is inserted into the string where the format specifier is. when you print the value of an objects, the object has already been allocated.

As you mentioned above that @ is used for creating literal objects. So where are we creating objects in NSLog? This is confusing me.

Stone Preston
Stone Preston
42,016 Points

yes @ is used for creating literal objects, except when they are used in a format specifier (followed by a percent sign). so there are 2 @ signs in the NSLog statement. the first one is the one that creates the NSString literal. this one NSLog(@"...

the second one is part of the format specifier (you know that because its after the percent sign

"this is an object: %@", someObject);

Thanks Stone , I understand it now ....