nsstring in objective c - objective-c

i am a beginer in objective c.i found the following line in code and is not able to understand what it does it do, as storeselect has not been used anywhere in the code.
NSString *storeSelect=#"";

Objective-C builds on C language. In C, quotes are placed around string literals, i.e. "hello". To distinguish NSString and C strings (char pointers, char *), Objective-C uses # in front of strings, so #"" is simply empty NSString. If there was no #, it would be empty C string, e.g. char *myString = "hello world";.

storeSelect is the name of a variable whose type is NSString *, with the value assigned to #""

It's just assigning an empty string to a variable named storeSelect. The #"" is for constant strings.

NSString *storeSelect=#"Hello World";
is a shortcut of -
NSString *str = [NSString stringWithCString:"Hello World"];
as "stringWithCString" is convenience method it will be automatically adds autoreleased.

Related

objective-c - Why can I assign values to pointers?

I understand pointers work with addresses and not the data itself. This is why I need to use the address-of (&) operator below as I need to assign the address of num to the pointer and not the actual value of num (40).
int num = 40;
int *numPtr = #
Therefore i'm confused as to why I can do this.
NSString *str = #"hello";
I've created a pointer str but instead of giving it an address i'm able to assign it some data, a literal string.
I thought pointers could only hold memory addresses so why am I able to directly assign it some data?
For someone trying to get their head around pointers and objects this is very confusing.
No you are not assigning a literal string to it, # makes a NSString object with the string value hello.
In most C languages strings are just an array of char, where char is a primitive type like int like in your example.
There is a reason you put an # before string literals (when you want an NSString and not a C string) in objective-c
#"String" is basically equivalent to [NSString stringWithCString:"string"] which returns a pointer to an NSString object containing the value "string"
It is the same way 1 is a c type integer, but #1 is a NSNumber representing the value of 1. If you see an # it means "this is shorthand for creating an object". (#[] for NSArrays, #{} for NSDictionarys, #(), #123, #YES, #NO for NSNumbers, and #"" for NSString)
C does not have strings. Usually char arrays are used to represent them.
NSString *str = #"hello";
can be thought of as short hand (literal) for:
char charArray[] = "hello";
NSString *str = [[NSString alloc] initWithBytes:charArray length:sizeof(charArray) encoding:NSUTF8StringEncoding]; // disregard character encoding for this example
or
unichar bla[] = {'h', 'e', 'l', 'l', 'o'};
str = [[NSString alloc] initWithCharacters:bla length:sizeof(bla)];
So an object is created and thus you need a pointer.

Can't manipulate a string?

NSString *string = #"HELLO";
For some reason, XCode won't auto-complete methods like remove characters or append etc... If that's the case, how can I, say, remove certain characters from my string? Say I want to remove all the L's.
NSString doesn't respond to those methods. NSMutableString does, but you've declared an immutable string variable and assigned to it a string literal. Since an Objective-C #"string literal" is always immutable (an instance of NSString but not NSMutableString), there's no way those messages can be sent to the object you're using.
If you want a mutable string, try:
NSMutableString *mutableString = [[#"HELLO" mutableCopy] autorelease];
That's an immutable string literal.
Here is a great post explaining it in further details:
What's the difference between a string constant and a string literal?
As for your question on how would you change it and remove the Ls:
NSString *hello = #"HELLO";
NSString *subString = [hello stringByReplacingOccurrencesOfString:#"L" withString:#""];
NSLog(#"subString: %#", subString);
That outputs "HEO"
Either that or you can create an NSMutableString by creating a copy of the mutable string like Jonathan mentioned. In both examples, you're copying it into a non-literal string.

Are strings defined as constants not NSStrings?

I have a constant defined as:
#define BEGIN_IMPORT_STRING #"Importing Hands!";
But I get an error when I try to concat with:
NSString *updateStr = [NSString stringWithFormat:#"%#%#", BEGIN_IMPORT_STRING, #" - Reading "];
This doesn't happen if I replace it with a string literal
NSString *updateStr = [NSString stringWithFormat:#"%#%#", #"foo", #" - Reading "];
Or a local string
NSString *temp = #"foo";
NSString *updateStr = [NSString stringWithFormat:#"%#%#", temp, #" - Reading "];
You need to remove the semicolon from your #define:
#define BEGIN_IMPORT_STRING #"Importing Hands!"
To the compiler, the resulting line looks like this:
NSString *updateStr = [NSString stringWithFormat:#"Importing Hands!";, #" - Reading "];
Replace
#define BEGIN_IMPORT_STRING #"Importing Hands!";
with
#define BEGIN_IMPORT_STRING #"Importing Hands!"
This is because compiler in your case replaces all occurrences of BEGIN_IMPORT_STRING with #"Importing Hands!";
Aside from the accepted answer (remove semicolon), note that:
#"Foo" is an NSString. You can even send it a message.
#define FOO #"Foo" is a preprocessor macro, not a constant. It's a typing shortcut.
Though macros aren't an uncommon way to avoid retyping the same string, they're an unfortunate holdover. Essentially, they're playing games that aren't necessary anymore.
For repeated strings, I prefer:
static NSString *const Foo = #"Foo;
The const portion of this definition ensures that the pointer is locked down, so that Foo can't be made to point to a different object.
The static portion restricts the scope to the file. If you want to access it from other files, remove the static and add the following declaration to your header file:
extern NSString *const Foo;
Should you be using
NSLocalizedString(#"Importing Hands!", #"Message shown when importing of hands starts");
?
I put it as an answer because this looks like something you would not want to have to go and redo through all your code.

Append char to an existing string Objective - C

I'm trying to append and programmatically modify a NSString on the fly. I'd like to know a couple of things:
How do I modify specific chars in a defined NSString?
How do I add chars in a defined NSString?
For example if I have the following defined: NSString *word = [[NSString alloc] initWithString:#"Hello"]; how would I be able to replace the letter "e" with "a" and also how would I add another char to the string itself?
Nerver use NSString for string manipulation,Use NSMutableString.
NSMutableString is the subclass of NSString and used for that purpose.
From Apple Documentation:
The NSString class declares the programmatic interface for an object that manages immutable strings. (An immutable string is a text string that is defined when it is created and subsequently cannot be changed. NSString is implemented to represent an array of Unicode characters (in other words, a text string).
The mutable subclass of NSString is NSMutableString.
NSMutableString *word = [[NSMutableString alloc] initWithString:#"Hello"];
//Replace a character
NSString* word2 = [word stringByReplacingOccurrencesOfString:#"e" withString:#"a"];
[word release];
word = nil ;
word = [[NSMutableString alloc] initWithString:word2 ];
//Append a Character
[word appendString:#"a"];
There are more string manipulating function See Apple Documentation for NSMutableString
Edited:
you could first use rangeOfString to get the range of the string (in your case #"e").
- (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask
then check the NSRange object if it's valid then use the replaceCharactersInRange function on your NSMutableString to replace the set of characters with your string.
- (void)replaceCharactersInRange:(NSRange)aRange withString:(NSString *)aString
NSString instances are immutable. You can create new NSString instances by appending or replacing characters in another like this:
NSString *foo = #"Foo";
NSString *bar = #"Bar";
NSString *foobar = [foo stringByAppendingString:bar];
NSString *baz = [bar stringByReplacingOccurrencesOfString:#"r" withString:#"z"];
If you really need to modify an instance directly, you can use an NSMutableString instead of an NSString.
If you really want to use primitive characters, NSString has a couple of initializers that can take character arrays (e.g. initWithCharacters:length:).
First things first:
If you are going to modify an string, you have to use NSMutableString. NSStrings can't be modified, hence they have a modifiable companion.
Then, NSMutableString has two methods that you are going to find helpful:
replaceCharactersInRange:withString
deleteCharactersInRange:
(Sorry for not linking directly to those method's links. StackOverflow if always imposing limitations to me as a new user...).
Just to add, NSMutableString has a method called appendFormat, which can be of great help when appending stuff:
[str appendFormat:#"%#-%#-%#", #"1", #"2",#"3"]
will append "1-2-3" to to str

Objective-C: initWithName:(char *)string

How would you read this in English? My concern is with the pointer. Is that pointer associated with char or with string?
Thanks in advance!
it's a pointer to char parameter named string.
So:
char * is the type of the parameter following it
string is the name of the parameter (and you should refer to this one in method body)
The part in parentheses describes the type of the parameter immediately following it—in this case, a pointer to some chars.
string is just the name of the parameter.
The type of the parameter is a pointer to a char.
The parameter is a C string, which is also named string.
[obj initWithName: "whatever"];
C strings are a '\0' terminated sequence of chars, and are declared as char *.
char *foo = "a C string";
NSString *bar = #"an objc string";