153

I'm learning objective-c and keep bumping into the @ symbol. It is used in different scenarios, for example at the start of a string or to synthesise accessor methods.

What's does the @ symbol mean in objective-c?

1
  • why @ is used before @interface and @end?
    – Kumar
    Jul 22, 2015 at 8:02

5 Answers 5

162

The @ character isn't used in C or C++ identifiers, so it's used to introduce Objective-C language keywords in a way that won't conflict with the other languages' keywords. This enables the "Objective" part of the language to freely intermix with the C or C++ part.

Thus with very few exceptions, any time you see @ in some Objective-C code, you're looking at Objective-C constructs rather than C or C++ constructs.

The major exceptions are id, Class, nil, and Nil, which are generally treated as language keywords even though they may also have a typedef or #define behind them. For example, the compiler actually does treat id specially in terms of the pointer type conversion rules it applies to declarations, as well as to the decision of whether to generate GC write barriers.

Other exceptions are in, out, inout, oneway, byref, and bycopy; these are used as storage class annotations on method parameter and return types to make Distributed Objects more efficient. (They become part of the method signature available from the runtime, which DO can look at to determine how to best serialize a transaction.) There are also the attributes within @property declarations, copy, retain, assign, readonly, readwrite, nonatomic, getter, and setter; those are only valid within the attribute section of a @property declaration.

10
  • 5
    Can you explain something about what @(expression) do? It's the only item I don't understand in the popup shown when I type @ in xcode. Jul 28, 2014 at 13:57
  • 13
    @(99) is the same as [NSNumber numberWithInteger:99]. @(YES) is the same as [NSNumber numberWithBool:YES]. The @ sign is a shortcut to creating objects.
    – JoJo
    Sep 30, 2015 at 15:32
  • 12
    Is anyone else confused by the fact that this "answer" doesn't really answer the stated question? The asker says "what does '@' mean in Objective-C?" and the answerer says "It means you're using Objective-C." I think he already knew as much... Aug 23, 2018 at 13:44
  • 1
    Sort of arbitrary; it needed to be in the base ASCII set and not already used by C when the first Objective-C preprocessor was being written. That’s why it’s @. Apr 9, 2019 at 5:33
  • 1
    Jon McClung: Leo is correct, there’s no “deeper meaning.” The @ character was unused by C, so it was a convenient “escape hatch” to alternative parsing that also preserved 100% compatibility with existing C code. Apr 9, 2019 at 5:36
69

From Objective-C Tutorial: The @ Symbol, the reason it is on the front of various keywords:

Using @ should make it easier to bolt an Objective-C compiler on to an existing C compiler. Because the @ isn't valid in any context in C except a string literal, the tokenizer (an early and simple step in the compiler) could be modified to simply look for the @ character outside of a string constant (the tokenizer understands string literals, so it is in a position to distinguish this). When @ is encountered the tokenizer would put the rest of the compiler in "Objective-C mode." (The Objective-C parser would be responsible for returning the compiler back to regular C mode when it detects the end of the Objective-C code).

Also when seen in front of a string literal, it makes an NSString rather than a 'char *' in C.

27

From Macrumors: Objective-C Tutorial, when in front of string literal:

There are also @"" NSString literals. It is essentially shorthand for NSString's +stringWithUTF8String method.

The @ also adds unicode support to C strings.

1
  • 14
    "It is essentially shorthand for NSString's +stringWithUTF8String method." Well, not exactly. The strings are statically allocated, which makes them different from +[NSString stringWithUTF8String:] (those are dynamically allocated), and release and retain have no effect on them.
    – user142019
    Oct 31, 2011 at 19:27
20

From the manual:

Objective-C frameworks typically do not use C-style strings. Instead, they pass strings around as NSString objects.

The NSString class provides an object wrapper for strings that has all of the advantages you would expect, including built-in memory management for storing arbitrary-length strings, support for Unicode, printf-style formatting utilities, and more. Because such strings are used commonly though, Objective-C provides a shorthand notation for creating NSString objects from constant values. To use this shorthand, all you have to do is precede a normal, double-quoted string with the @ symbol, as shown in the following examples:

NSString *myString = @"My String\n";
NSString *anotherString = [NSString stringWithFormat:@"%d %@", 1, @"String"];
1
  • 4
    But this is only one example of where @is used. I'm looking at code like this: mapperOptions = @{ kSTMapperVolumeResolutionKey: @(volumeResolution), ... nothing to do with NSString Jan 3, 2017 at 4:37
5

As other answers have noted, the @ symbol was convenient for adding Objective-C's superset of functionality to C because @ is not used syntactically by C.

As to what it represents, that depends on the context in which it is used. The uses fall roughly into two categories (keywords and literals), and I've summarized the uses I could find below.

I wrote most of this before finding NSHipster's great summary. Here's another less thorough cheat sheet. (Both of those sources call things prefixed with @ "compiler directives", but I thought compiler directives were things like #define, #ifdef, etc. If someone could weigh in on the correct terminology, I'd appreciate it.)

Objective-C Keywords

@ prefixes many Objective-C keywords:

  • @interface: declares the methods and properties associated with a class
  • @implementation: implements a class's declarations from @interface
  • @protocol/@optional/@required: declares methods and properties that are independent of any specific class.
  • @class: forward declaration of a class
  • @property/@synthesize/@dynamic: declare properties in an @interface
  • @try/@throw/@catch/@finally: exception handling
  • @end: closes @interface, @implementation, and @protocol.
  • @encode: returns a C string that encodes the internal representation of a given type
  • @synchronized: ensures parallel execution exclusivity
  • @selector/@protocol: return SEL or protocol pointers with a specified name
  • @defs: I'm not really sure; it appears to import Objective-C class properties into a struct. NSHipster's page says it does not exist in modern Objective-C.
  • @public/@package/@protected/@private: access modifiers
  • @available: checks API availability.
  • @autoreleasepool: creates a new autorelease scope. Any objects that received an autorelease in the block will receive a release after exiting the block (and not before.)

Objective-C Literals

@ creates Objective-C literals:

  • @...: NSNumber literal

    NSNumber *fortyTwo = @42;             // equivalent to [NSNumber numberWithInt:42]
    NSNumber *yesNumber = @YES;           // equivalent to [NSNumber numberWithBool:YES]
    
  • @(...): Boxed expressions

    // numbers.
    NSNumber *piOverTwo = @(M_PI / 2);        // [NSNumber numberWithDouble:(M_PI / 2)]
    // strings.
    NSString *path = @(getenv("PATH"));       // [NSString stringWithUTF8String:(getenv("PATH"))]
    // structs.
    NSValue *center = @(view.center);         // Point p = view.center;
                                              // [NSValue valueWithBytes:&p objCType:@encode(Point)];
    
  • @"...": Boxed C strings

  • @[]/@{}: Container literals

    NSArray *array = @[ @"Hello", NSApp, [NSNumber numberWithInt:42] ];
    NSDictionary *dictionary = @{
      @"name" : NSUserName(),
      @"date" : [NSDate date],
      @"processInfo" : [NSProcessInfo processInfo]
    };
    

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.