What is the # symbol used for in objective-C? [duplicate] - 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?

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.

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.

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.

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

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

Related

What does #() mean in Objective-C?

For example,
CABasicAnimation *rotate = [CABasicAnimation animationWithKeyPath:#"transform.rotation"];
[rotate setToValue:#(M_PI)];
[rotate setDuration:0.1f];
[[aView layer] addAnimation:rotate forKey:#"myRotationAnimation"];
where M_PI is defined as a macro in math.h,
#define M_PI 3.14159265358979323846264338327950288 /* pi */
It's a pointer to an NSNumber object. It's called a boxed literal, because the mental picture is of putting a primitive value of expression inside into a "box", that is, an object.
See official documentation if in doubt. Note that pointer can be to a "real" NSNumber object or it can (theoretically, don't know whether this will work in practice) be a tagged pointer (see, e.g., my question).
Note that you can also do things like #"string" and #5, which will create constants in compile time. But you need parentheses to use something which is not a literal, e.g. #(2 + 3). Parentheses form can be used for any expression, even those that compiler cannot compute at compile-time (although if it can, it will just put an expression result into code).
NeXT and Apple Obj-C runtimes have long included a short-form way to create new strings, using the literal syntax #"a new string". Using this format saves the programmer from having to use the longer initWithString or similar methods when doing certain operations.
When using Apple LLVM compiler 4.0 or later, arrays, dictionaries, and numbers (NSArray, NSDictionary, NSNumber classes) can also be created using literal syntax instead of methods. Literal syntax uses the # symbol combined with [], {}, (), to create the classes mentioned above, respectively.
So, basically it's not only for id or NSNumber object!
thanks to wiki.
It's Shorthand writing
In Objective-C, any character, numeric or boolean literal prefixed with the '#' character will evaluate to a pointer to an NSNumber object (In this case), initialized with that value. Cā€™s type suffixes may be used to control the size of numeric literals.
'#' is used a lot in the objective-C world. It is mostly used to avoid taking english words and making them reserved (for example, you can't have a variable called float in C/Objective-C because this is a reserved word).
Use this link To have detailed knowledge of '#' symbol.
In Modern Objective C, '#' symbol is used extensively.
What You can do with it:
calculate an expression: #(<Expression>)
wrap any value like int,bool,float,char in same way
Reasons to use:
Easy to write, Less code required
Less chances of mistakes. Compare [NSNumber numberWithInt:3] with #3.
Get rid of typecasting issues in simple cases.
It represent id Object
that you can use any expression in it or return any object.
Syntax : #(<#expression#>) it will return id object.
So in your case it will returning NSNumber object to setToValue method.

Is the '#' that precedes NSStrings actually an overloaded operator?

When dealing with NSStrings we always need to include de # at the beginning of the string.
For example:
NSString *string = #"Hello, World!";
string is an object of the class NSString.
Just crossed my mind that # could be and overloaded operator that transforms the C string into an object of the class NSString.
Is it so? Or is it just a reverie of my noob mind?
# is the indicator to the compiler that you are declaring some kind of literal. NSString (#"") isn't the only one, NSDictionary (#{}), NSArray (#[]) and NSNumber (#1, #YES) also have defined literal definitions.
From here:
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).
From the manual:
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"];
// Create an Objective-C string from a C string
NSString *fromCString = [NSString stringWithCString:"A C string" encoding:NSASCIIStringEncoding];

Why does NSString use an #? [duplicate]

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?
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.
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.
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.
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"];
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]
};

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?
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.
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.
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.
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"];
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]
};

What's the difference between a string constant and a string literal?

I'm learning objective-C and Cocoa and have come across this statement:
The Cocoa frameworks expect that global string constants rather than string literals are used for dictionary keys, notification and exception names, and some method parameters that take strings.
I've only worked in higher level languages so have never had to consider the details of strings that much. What's the difference between a string constant and string literal?
In Objective-C, the syntax #"foo" is an immutable, literal instance of NSString. It does not make a constant string from a string literal as Mike assume.
Objective-C compilers typically do intern literal strings within compilation units ā€” that is, they coalesce multiple uses of the same literal string ā€” and it's possible for the linker to do additional interning across the compilation units that are directly linked into a single binary. (Since Cocoa distinguishes between mutable and immutable strings, and literal strings are always also immutable, this can be straightforward and safe.)
Constant strings on the other hand are typically declared and defined using syntax like this:
// MyExample.h - declaration, other code references this
extern NSString * const MyExampleNotification;
// MyExample.m - definition, compiled for other code to reference
NSString * const MyExampleNotification = #"MyExampleNotification";
The point of the syntactic exercise here is that you can make uses of the string efficient by ensuring that there's only one instance of that string in use even across multiple frameworks (shared libraries) in the same address space. (The placement of the const keyword matters; it guarantees that the pointer itself is guaranteed to be constant.)
While burning memory isn't as big a deal as it may have been in the days of 25MHz 68030 workstations with 8MB of RAM, comparing strings for equality can take time. Ensuring that most of the time strings that are equal will also be pointer-equal helps.
Say, for example, you want to subscribe to notifications from an object by name. If you use non-constant strings for the names, the NSNotificationCenter posting the notification could wind up doing a lot of byte-by-byte string comparisons when determining who is interested in it. If most of these comparisons are short-circuited because the strings being compared have the same pointer, that can be a big win.
Some definitions
A literal is a value, which is immutable by definition. eg: 10
A constant is a read-only variable or pointer. eg: const int age = 10;
A string literal is a expression like #"". The compiler will replace this with an instance of NSString.
A string constant is a read-only pointer to NSString. eg: NSString *const name = #"John";
Some comments on the last line:
That's a constant pointer, not a constant object1. objc_sendMsg2 doesn't care if you qualify the object with const. If you want an immutable object, you have to code that immutability inside the object3.
All #"" expressions are indeed immutable. They are replaced4 at compile time with instances of NSConstantString, which is a specialized subclass of NSString with a fixed memory layout5. This also explains why NSString is the only object that can be initialized at compile time6.
A constant string would be const NSString* name = #"John"; which is equivalent to NSString const* name= #"John";. Here, both syntax and programmer intention are wrong: const <object> is ignored, and the NSString instance (NSConstantString) was already immutable.
1 The keyword const applies applies to whatever is immediately to its left. If there is nothing to its left, it applies to whatever is immediately to its right.
2 This is the function that the runtime uses to send all messages in Objective-C, and therefore what you can use to change the state of an object.
3 Example: in const NSMutableArray *array = [NSMutableArray new]; [array removeAllObjects]; const doesn't prevent the last statement.
4 The LLVM code that rewrites the expression is RewriteModernObjC::RewriteObjCStringLiteral in RewriteModernObjC.cpp.
5 To see the NSConstantString definition, cmd+click it in Xcode.
6 Creating compile time constants for other classes would be easy but it would require the compiler to use a specialized subclass. This would break compatibility with older Objective-C versions.
Back to your quote
The Cocoa frameworks expect that global string constants rather than
string literals are used for dictionary keys, notification and
exception names, and some method parameters that take strings. You
should always prefer string constants over string literals when you
have a choice. By using string constants, you enlist the help of the
compiler to check your spelling and thus avoid runtime errors.
It says that literals are error prone. But it doesn't say that they are also slower. Compare:
// string literal
[dic objectForKey:#"a"];
// string constant
NSString *const a = #"a";
[dic objectForKey:a];
In the second case I'm using keys with const pointers, so instead [a isEqualToString:b], I can do (a==b). The implementation of isEqualToString: compares the hash and then runs the C function strcmp, so it is slower than comparing the pointers directly. Which is why constant strings are better: they are faster to compare and less prone to errors.
If you also want your constant string to be global, do it like this:
// header
extern NSString *const name;
// implementation
NSString *const name = #"john";
Let's use C++, since my Objective C is totally non-existent.
If you stash a string into a constant variable:
const std::string mystring = "my string";
Now when you call methods, you use my_string, you're using a string constant:
someMethod(mystring);
Or, you can call those methods with the string literal directly:
someMethod("my string");
The reason, presumably, that they encourage you to use string constants is because Objective C doesn't do "interning"; that is, when you use the same string literal in several places, it's actually a different pointer pointing to a separate copy of the string.
For dictionary keys, this makes a huge difference, because if I can see the two pointers are pointing to the same thing, that's much cheaper than having to do a whole string comparison to make sure the strings have equal value.
Edit: Mike, in C# strings are immutable, and literal strings with identical values all end pointing at the same string value. I imagine that's true for other languages as well that have immutable strings. In Ruby, which has mutable strings, they offer a new data-type: symbols ("foo" vs. :foo, where the former is a mutable string, and the latter is an immutable identifier often used for Hash keys).