Initializing a string, why is `#` required? [duplicate] - ios

This question already has answers here:
What does the # symbol represent in objective-c?
(5 answers)
Closed 9 years ago.
I'm really new to Objective-C but I'm experienced in C/C++, so a few things look strange to me. I'm reading a tutorial that shows the basics of Objective-C and the author warns me about forgetting to include the # before my string. So, for instance
"Hello" vs #"Hello"
However, the author doesn't explain why the # is required or what its syntactical meaning is. So that's what I'm asking now, what does the # do?

That's a NSString literal. Without the #, you'd be creating a char *, which is not an object like NSString.

Objective-C is a super set of C, so you should know "hello" is a C string (const char *).
#"hello" is something different, it is NSString *. NSString is ObjC object, that you can send message to it and use like object. You can't do it with C string.
for example, to get length from these two string:
NSString *objcStr = #"hello";
int len = [objcStr length];
const char * cStr = "hello";
len = strlen(cStr);

The use of # designates features that are unique to Objective C and are not in raw C. In this case, if you want an Objective C NSString object as a literal, you use # otherwise you end up with a different type of character string that is not an Objective C object but rather a raw C entity.

Related

How long has NSString concatenation been supported?

I've just come across this line in some legacy code I'm editing:
[UIImage imageNamed:#"data/visuals/interface/" #"backgroundViewController"];
^^^^
"Oops, what have I done here?"
I thought I must have accidentally just pasted something in the wrong place, but an undo didn't change that line. Out of curiosity, I built the program and it was successful!
Whaddyaknow? Obj-c has a more succinct way of concatenating string literals.
I added some more tests:
A simple log
NSLog(#"data/visuals/interface/" #"backgroundViewController");
data/visuals/interface/backgroundViewController
In parameters
NSURL *url = [NSURL URLWithString:#"http://" #"test.com" #"/path"];
NSLog(#"URL:%#", url);
URL:http://test.com/path
Using Variables
NSString *s = #"string1";
NSString *s2 = #"string2";
NSLog(#"%#", s s2);
Doesn't compile (not surprised by this one)
Other literals
NSNumber *number = #1 #2;
Doesn't compile
Some questions
Is this string concatenation documented anywhere?
How long has it been supported?
What is the underlying implementation? I expect it will be [s1 stringByAppendingString:s2]
Is it considered good practice by any authoritative body?
This method of concatenating static NSStrings is a compile-time compiler capability that has been available for over ten years. It is usually used to allow long constant strings to be split over several lines. Similar capabilities have been available in "C" for decades.
In the C Programming Language book, 1988 second edition, page 38 describes string concatenation so it has been around for a long time.
Excerpt from the book:
String constants can be concatenated at compile time:
"hello," " world" is equivalent to "hello, world"
This is useful for spitting long strings across several source lines.
Objective-C is a strict superset of "C" so it has always supported "C" string concatenation and my guess is that because of that static NSString concatenation has always been available.
It is considered good practice when used to split a static string across several lines for readability.

How to read a char in Vala?

I'm programming in Vala language and I've a problem: I don't know how to read a char (although I know how to read a string and an integer).
string name = stdin.read_line();
int maximum = int.parse(stdin.read_line());
char option = ????;
One option is using scanf(), but if I use it I have problems during execution time.
If you just want to read a single character from a GLib.FileStream, you can use GLib.FileStream.getc, which "reads the next character from stream and returns it as an unsigned char cast to an int, or EOF on end of file or error." Actually, GLib.FileStream.read_line is implemented using getc. So, the "????" in your question would be something like (char) stdin.getc().
If you are trying to interact with a user, note that input is typically buffered by the terminal until the end of a line. If you want to get a character immediately after the user presses a key you'll need to use something like ncurses (for which Vala bindings are distributed with valac).

How to convert from array of char to NSString in Objective-C [duplicate]

This question already has answers here:
How to read input from the keyboard in Objective-C
(3 answers)
Closed 9 years ago.
I'm trying to read an input of type NSString from the user but I couldn't find the format specifier for NSString, I know that %i is for integer variables, but which one is for NSString?
As a result, I created an array of char, read the input from a user, but I couldn't convert it to NSString and XCode gives me as an output weird things like ø¿_ÿ and sometimes (null) I have used many string encodings like (none of them worked):
NSASCIIStringEncoding
NSNEXTSTEPStringEncoding
NSJapaneseEUCStringEncoding
NSUTF8StringEncoding
NSISOLatin1StringEncoding
NSSymbolStringEncoding
NSNonLossyASCIIStringEncoding
NSShiftJISStringEncoding
NSISOLatin2StringEncoding
NSUnicodeStringEncoding
NSWindowsCP1251StringEncoding
NSWindowsCP1252StringEncoding
NSWindowsCP1253StringEncoding
NSWindowsCP1254StringEncoding
NSWindowsCP1250StringEncoding
NSISO2022JPStringEncoding
NSMacOSRomanStringEncoding
NSUTF16StringEncoding
NSUTF16BigEndianStringEncoding
NSUTF16LittleEndianStringEncoding
NSUTF32StringEncoding = 0x8c000100
NSUTF32BigEndianStringEncoding
NSUTF32LittleEndianStringEncoding
NSProprietaryStringEncoding
Could anyone tell me why?
This is my code:
//I have declared a class and called it Labtop
Labtop *myLabtop;
myLabtop = [[Labtop alloc] init];
char input[30];
NSLog(#"Hello,please enter which brand you will use this time:\n");
input[29] = getchar();// read the input from the user
NSString *b =[[NSString alloc] initWithCString:input encoding:NSISOLatin1StringEncoding];//convert from array char to NSString
[myLabtop labtopBrand:b];//labtopBrand fund will print what the user has entered
The result is:
Hello,please enter which brand you will use this time:
MacBook //this is the user's input
I will use  ø¿_ÿ//this what Xcode shows me as an output Program ended
with exit code: 0
Format specifier for NSString is %#
There are some problems here. First off, getchar() returns one character, not a whole string. Second, this line:
input[29] = getchar();// read the input from the user
Just assigns the last character in input to the character the user types, which probably isn’t what you want at all. Maybe you meant gets()? Except you really shouldn’t use that since it has no bounds checking, and you still wouldn’t want to assign the results to the thirtieth character in your array. Maybe look at getline() instead.
Also, you’ll probably want to specify NSUTF8StringEncoding.
Good luck, keep experimenting!

Unichar with specific characters [duplicate]

This question already has answers here:
Objective c doesn't like my unichars?
(3 answers)
Closed 9 years ago.
I'm trying to add some specific characters to my
unichar rusLetter [] = { 'Ж', 'Й', }
I want actually to add all letters from russian alphabet. Using above line of code, i get an error:
Character too large for enclosing character literal type
Any ideas how to fix that? And maybe there is an easier way to add all letters, not to type all of them.
Thanks
the ' literal (single quote) means a char and that is too small to hold the symbols.
In ObjC use an NSString to hold it
NSString *rusLetters = #"ЖЙ";
unichar c1 = [rusLetters characterAtIndex:0];
unichar c2 = [rusLetters characterAtIndex:1];

what does this return parameter means?

+(const char /*wchar_t*/ *)wcharFromString:(NSString *)string
{
return [string cStringUsingEncoding:NSUTF8StringEncoding];
}
Does it return char or wchar_t?
from the method name, it should return wchar_t, but why there is a comment around wchar_t return type?
Source is here:
How to convert wchar_t to NSString?
That code just looks incorrect. They're claiming it does one thing, but it actually does another. The return type is const char *.
This method is not correct. It returns a const char *, encoded as a UTF8 string. That is a perfectly sensible way of getting a C string from an NSString, but nowhere here is anyone actually doing anything with wchar_ts.
wchar_t is a "wide char", and a pointer to it would be a "wide string" (represented by const wchar_t *). These are designed to precisely represent larger character sets, and can be two-byte wide character strings; they use a whole different variant set of string manipulation functions to do things with them. (Strings like this are very rarely seen in iOS development, for what it's worth.)

Resources