In Objective-C, I can write:
id pString = @"Hello, World.";
and the compiler will instantiate an NSString without me needing to explicitly call a factory method. However, NSString is really just a Foundation class and thus presumably not part of the actual Objective-C language definition.
So when I write @"String"
, how does the compiler know to build an NSString in particular, and not some other string-like object? In other words, where does the Objective-C language stop and the Foundation library start?
(NSString *) is simply the type of the argument - a string object, which is the NSString class in Cocoa. In Objective-C you're always dealing with object references (pointers), so the "*" indicates that the argument is a reference to an NSString object.
A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior.
The Swift string is one character long, as expected. The NSString says it has a length of seven — this matches with the length of the Swift string's utf16 view, since NSStrings are backed by UTF-16: 09:02 The Swift string's unicodeScalars view returns a count of four.
If you create an object using a method that begins with init, new, copy, or mutableCopy, then you own that object and are responsible for releasing it (or autoreleasing it) when you're done with it. If you create an object using any other method, that object is autoreleased, and you don't need to release it.
When you write Objective-C code outside of Cocoa or GNUStep environments, @"..."
is not linked to NSString
.
In this case, gcc provides an option for specifying a class associated to literal strings:
-fconstant-string-class=class-name
Use class-name as the name of the class to instantiate for each
literal string specified with the syntax "@"..."". The default
class name is "NXConstantString".
The @""
directive appears to be built-in to the objective-c compiler.
For instance, if you remove all #import
s from your .m source file (& prefix header), the following line will be a syntax error:
NSString *string = @"ABCD"; // (Doesn't know anything about NSString class)
However, if you change the Foundation NSString
type to the built-in void
type, it will compile just fine:
void *string = @"ABCD";
So, even without Foundation's NSString
definition, the compiler knows how to turn @""
into something that can become an NSString
instance at runtime (it probably won't instantiate without Foundation, but the compiler doesn't seem to mind); Since it accepts the syntax without needing any external library definitions, the compiler sees @""
as part of the language.
Your code, however, won't be able to make use of any @""
instance without importing Foundation.h, so from the point of view of your program, @""
is part of the library.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With