Is it necessary to assign a string to a variable before comparing it to another? - objective-c

I want to compare the value of an NSString to the string "Wrong". Here is my code:
NSString *wrongTxt = [[NSString alloc] initWithFormat:#"Wrong"];
if( [statusString isEqualToString:wrongTxt] ){
doSomething;
}
Do I really have to create an NSString for "Wrong"?
Also, can I compare the value of a UILabel's text to a string without assigning the label value to a string?

Do I really have to create an NSString for "Wrong"?
No, why not just do:
if([statusString isEqualToString:#"Wrong"]){
//doSomething;
}
Using #"" simply creates a string literal, which is a valid NSString.
Also, can I compare the value of a UILabel.text to a string without assigning the label value to a string?
Yes, you can do something like:
UILabel *label = ...;
if([someString isEqualToString:label.text]) {
// Do stuff here
}

if ([statusString isEqualToString:#"Wrong"]) {
// do something
}

Brian, also worth throwing in here - the others are of course correct that you don't need to declare a string variable. However, next time you want to declare a string you don't need to do the following:
NSString *myString = [[NSString alloc] initWithFormat:#"SomeText"];
Although the above does work, it provides a retained NSString variable which you will then need to explicitly release after you've finished using it.
Next time you want a string variable you can use the "#" symbol in a much more convenient way:
NSString *myString = #"SomeText";
This will be autoreleased when you've finished with it so you'll avoid memory leaks too...
Hope that helps!

You can also use the NSString class methods which will also create an autoreleased instance and have more options like string formatting:
NSString *myString = [NSString stringWithString:#"abc"];
NSString *myString = [NSString stringWithFormat:#"abc %d efg", 42];

Related

Inserting text into the string in iOS

I need my user to enter numbers to type his telephone number.The user can only enter 8 numbers(for eg. XXXXXXXX). I need to change the phone number to be in the format XX-XX-XXXX.
This is what I have tried:
[tfDID.text insertString:#"-" atIndex:2];
[tfDID.text insertString:#"-" atIndex:5];
But it is returning me an error saying:
No Visible #interface for 'NSString' declares the selector 'insertString:atIndex:'
Need some guidance on this. Sorry if this is a stupid question.
No Visible #interface for 'NSString' declares the selector 'insertString:atIndex:'
As you are trying to mutate the textbox's value, which returns you NSString.
NSString object can not be mutated, so convert it into a mutable string then manupulate it.
Make your string NSMutableString.
As,
NSMutableString *tfDIDString=[NSMutableString stringWithString:tfDID.text];
[tfDIDString insertString:#"-" atIndex:2];
[tfDIDString insertString:#"-" atIndex:5];
[UITextField text] is NSString, you need to declare local variable of NSMutableString and perform insertString operations on it
Hope it helps you
Implement <UITextFieldDelegate> and then do:
-(void)textFieldDidChange:(UITextField*)textField
{
if( textField.text.length == 2 || textField.text.length == 5 ){
textField.text = [textField.text stringByAppendingString:#"-"];
}
}
Completely agree with the answer suggesting making it a mutable string.
Just to play devils advocate you could do:
NSString *partOne = [NSString stringWithRange:NSMakeRange(0,2)];
NSString *partTwo = [NSString stringWithRange:NSMakeRange(2,2)];
NSString *partThree = [NSString stringWithRange:NSMakeRange(4,4)];
NSString *formattedNumber = [NSString stringWithFormat:#"%#-%#-%#",partOne,partTwo,partThree];
I've written it out longhand but you could compress the string declarations for the parts in to the stringWithFormat call if you don't mind nesting and sacrifcing a bit of readability.

NSString type declaration

I'm studying Objective-C. Can you tell me what is the difference (if any) between these NSString declarations?
NSString *firstString;
firstString = #"First string";
NSString *secondString = [NSString string];
secondString = #"Second string";
The second one creates two strings, and throws the first one away without using it. In this line:
NSString *secondString = [NSString string];
you are creating a new string, which isn't really useful because it's empty, and you're assigning it to secondString. Then you're assigning a different string (#"Second String") to secondString.
There's no need to do this. In either case, you can just write:
NSString *myString = #"MyString";
The syntax #"Some string here" is called a string literal, and it's a shorthand for specifying an NSString with an actual value in your code.
No difference as the end result.
The first string is being declared and then assigned a value via the string literal syntax (you can also do this with NSNumbers as of Xcode 4.4).
The second is being initialised as a string (empty) and then is being assigned another NSString object. In this case there are actually two NSString objects being created, the former - [NSString string] is being overwritten by the latter #"string value"
So, the first one is nil to start with and then has a value. The second had a instantiated NSString object to start and was then overwritten.
In the end both string objects are the same, but obviously you are wasting resources in the second case.

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.

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

stringByAppendingFormat not working

I have an NSString and fail to apply the following statement:
NSString *myString = #"some text";
[myString stringByAppendingFormat:#"some text = %d", 3];
no log or error, the string just doesn't get changed. I already tried with NSString (as documented) and NSMutableString.
any clues most welcome.
I would suggest correcting to (documentation):
NSString *myString = #"some text";
myString = [myString stringByAppendingFormat:#" = %d", 3];
From the docs:
Returns a string made by appending to the receiver a string constructed from a given format string and the following arguments.
It's working, you're just ignoring the return value, which is the string with the appended format. (See the docs.) You can't modify an NSString — to modify an NSMutableString, use -appendFormat: instead.
Of course, in your toy example, you could shorten it to this:
NSString *myString = [NSString stringWithFormat:#"some text = %d", 3];
However, it's likely that you need to append a format string to an existing string created elsewhere. In that case, and particularly if you're appending multiple parts, it's good to think about and balance the pros and cons of using a mutable string or several immutable, autoreleased strings.
Creating strings with #"" always results in immutable strings. If you want to create a new NSMutableString do it as following.
NSMutableString *myString = [NSMutableString stringWithString:#"some text"];
[myString appendFormat:#"some text = %d", 3];
I had a similar warning message while appending a localized string. This is how I resolved it
NSString *msgBody = [msgBody stringByAppendingFormat:#"%#",NSLocalizedString(#"LOCALSTRINGMSG",#"Message Body")];