Benedict Cohen
Benedict Cohen

Reputation: 11920

What does the @ symbol represent in objective-c?

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?

Upvotes: 155

Views: 57742

Answers (5)

Carl G
Carl G

Reputation: 18250

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]
    };
    

Upvotes: 5

pabloelustondo
pabloelustondo

Reputation: 2216

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"];

Upvotes: 20

Van Nguyen
Van Nguyen

Reputation: 4059

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.

Upvotes: 28

Chris Hanson
Chris Hanson

Reputation: 55096

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.

Upvotes: 164

thelsdj
thelsdj

Reputation: 9144

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.

Upvotes: 70

Related Questions