Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a string in Objective-C?

How do I declare a simple string "test" to a variable?

like image 765
powtac Avatar asked Oct 14 '09 16:10

powtac


People also ask

How to declare string in Object C?

NSString from C Strings and Data To create an NSString object from a C string, you use methods such as initWithCString:encoding: . You must correctly specify the character encoding of the C string. Similar methods allow you to create string objects from characters in a variety of encodings.

How do I print a string in Objective C?

You can use %@ for all objects including NSString. This will in turn call the objects description method and print the appropriate string.

How do you get the first character of a string in Objective C?

You want: NSString *firstLetter = [codeString substringToIndex:1];

What is NSString?

A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior.


2 Answers

A C string is just like in C.

char myCString[] = "test"; 

An NSString uses the @ character:

NSString *myNSString = @"test"; 

If you need to manage the NSString's memory:

NSString *myNSString = [NSString stringWithFormat:@"test"]; NSString *myRetainedNSString = [[NSString alloc] initWithFormat:@"test"]; 

Or if you need an editable string:

NSMutableString *myMutableString = [NSMutableString stringWithFormat:@"test"]; 

You can read more from the Apple NSString documentation.

like image 180
Carl Norum Avatar answered Oct 08 '22 23:10

Carl Norum


NSString *testString = @"test"; 
like image 35
Jeff Kelley Avatar answered Oct 08 '22 22:10

Jeff Kelley