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];
Related
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]
};
I've been using Objective-C for a while now, but have never really understood what the purpose of the # symbol before all strings is. For instance, why do you have to declare a string like this:
NSString *string = #"This is a string";
and not like this:
NSString *anotherString = "This is another string";
as you do in Java or so many other programming languages. Is there a good reason?
It denotes a NSString (rather than a standard C string)
an NSString is an Object that stores a unicode string and provides a bunch of method to assist with manipulating.
a C string is just a \0 terminated bunch of characters (bytes).
EDIT: and the good reason is that Objective-C builds on top of C, the C language constructs need to be still available. #"" is an objective-c only extension.
I'm just beginning, and I'm a little hung up on this. I may have a fundamental misunderstanding with which you can kindly help me out.
Why is it that you can assign a string value to an NSString* (and, I'm sure, many other object types) directly? E.g.,
NSString* s = #"Hello, world!";
whereas the following code, I believe, would assign to s2 s1's pointer value (and therefore only incidentally provide s2 with a string value)?
NSString* s1 = #"Hello, world!";
NSString* s2 = s1;
For many objects, don't you have to indicate a property, a.k.a. instance variable, to which you want to assign a value (i.e., use a setter method)? Shouldn't the object itself accept assignments only of pointer values? Or do classes such as NSString automatically reinterpret code such as the first example above to assign the indicated string to an implied instance variable using an implied setter?
Why is it that you can assign a string value to an NSString* (and, I'm
sure, many other object types) directly?
Though it may look like it, you are not assigning the value of the string 'directly' to the instance variable. You are actually assigning the address of the string value to your instance variable. Now, the real question is what is going on behind the scenes when you have an expression of the type:
NSString * str = #"Hello World";
This expression represents the creation of a string literal. In C (and Objective-C which is a strict superset of C), string literals get special handling. Specifically, the following happens:
When your code is compiled the string "Hello World" will be created in the data section of
the program.
When the program is executing, an instance variable 'str' will be allocated on the heap.
The 'str' instance variable will be pointed at the static memory location where the actual string "Hello World" is stored.
The main difference between your first and second examples is that in the second example the memory for the string variable is dynamically allocated on the heap, at runtime. Note that in both cases the variable 'str' is just a pointer allocated dynamically.
More or less the latter. String literals like #"Hello World!" are treated as a special case in Objective-C: strings declared with that syntax are statically allocated, instantiated and cached at compile time to improve performance. From the programmer's perspective, it's no different from calling [NSString stringWithString:#"Hello World!"] or a constructor that takes a C-string -- you should just think of it as syntactic sugar.
FWIW, Objective-C has recently begun extending the # prefix to allow declaring dictionary and array literals as well, e.g.: #{ #"key" : #"value" } or #[ obj1, obj2, obj3 ].
This is a function of the compiler and not a language construct. The compiler in this case recognizes a string literal and inserts some code to produce the intended result.
#"" is essentially shorthand for NSString's +stringWithUTF8String method.
take from here:
What does the # symbol represent in objective-c?
NSString *s1 = #"Hello, world!";
is essentially equivalent to
NSString *s1 = [NSString stringWithUTF8String:"Hello, world!"];
The former allocates a new NSString object statically (instead of on the heap at runtime, as the latter would do).
It's important to note that these are just pointers. When you do NSString *s2 = s1, both s1 and s2 refer to the same object.
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]
};
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]
};