What does the @ symbol represent in objective-c?
Asked Answered
V

5

154

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?

Violoncello answered 25/8, 2008 at 7:57 Comment(1)
why @ is used before @interface and @end?Souther
A
164

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.

Atomics answered 25/8, 2008 at 8:36 Comment(10)
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.Archiplasm
@(99) is the same as [NSNumber numberWithInteger:99]. @(YES) is the same as [NSNumber numberWithBool:YES]. The @ sign is a shortcut to creating objects.Interferometer
NSLog(@"%@, %@", [@(9) class], [@[@(1),@(2)] class]); got output __NSCFNumber, __NSArrayIOutweigh
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...Photosensitive
@JonMcClung The choice of the @ character was most likely an arbitrary choice during language design. What deeper meaning are you looking for?Kuhns
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 @.Atomics
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.Atomics
@LeoNatan @ChrisHanson I don't know what @JonMcClung meant, but I have the same comment/question and by it I mean, what does "stand-alone" @ (not followed by a keyword) mean? I understand @interface and @end. I don't understand @"string literal" or @(9) or [@[@(1), @(2)]].Schouten
My intuition is that the answer is something like "@ was arbitrarily chosen to introduce Objective-C-specific constructs such as keywords. It also can be used preceding (some?) literal and expression values, to indicate <something>." :-)Schouten
@ColinFraizer It's a way to differentiate between primitive literals, such as ints and char arrays, and their object counterparts, such as NSNumbers, NSStrings, etc. This is known as "boxing". String literals have been available for long time, while number, array and dictionary literals were introduced later for less verbose code.Kuhns
A
70

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.

Alenealenson answered 25/8, 2008 at 8:4 Comment(0)
F
28

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.

Frisian answered 11/1, 2009 at 15:27 Comment(1)
"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.Larondalarosa
E
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"];
Erik answered 2/2, 2012 at 5:51 Comment(1)
But this is only one example of where @is used. I'm looking at code like this: mapperOptions = @{ kSTMapperVolumeResolutionKey: @(volumeResolution), ... nothing to do with NSStringUltravirus
S
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]
    };
    
Stillness answered 23/7, 2022 at 16:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.