I'm just learning how to code so thanks for your patience on this simple question.
Here's my code:
- (IBAction)buttonWasPressed:(id)sender {
NSString *buttonName = [sender titleForState:UIControlStateNormal];
if (buttonName == #"Button 1") {
do something
}
How do I compare the title of the button passed as sender to a string?
Much thanks for the help.
in objective-c you can't compare strings using "==",
instead you should use the method isEqualToString from the NSString class to compare a string with another.
if ([buttonName isEqualToString: #"Button 1"]) {
// do something
}
Use -isEqualToString method:
if ([buttonName isEqualToString:#"Button 1"])
...
using == you compare ponters, not the actual string values they contain
The better way to compare string is:
NSString *string1 = <your string>;
NSString *string2 = <your string>;
if ([string1 caseInsensitiveCompare:string2] == NSOrderedSame) {
//strings are same
} else {
//strings are not same
}
I've found that with Xcode 8.3.1, it is necessary to do:
if([self.myButton isEqual: #"My text"]) {
//do this
}
Related
When parsing API responses, sometimes I can not rely on strings being embedded in quotation marks. ID's are a good example of this, where some API's will send the numerical ID as a string while some will send it as a number.
What is a good practice when parsing such a value? If I simply parse it to an NSString like so:
NSString *myID = (NSString *)message["myID"];
I can end up with an NSString object that somehow contains (long)123.
And using stringValue would cause issues when the value is actually already sent as a string (since NSString does not have a stringValue function).
A way that works, but is somewhat ugly, is this:
id myID = (NSString *)message["myID"];
if ([myID respondsToSelector:#selector(stringValue)])
{
myID = [myID stringValue];
}
You could do something like:
id myID = message["myID"];
if ([myID isKindOfClass:[NSString class]]) { ... }
else { ... }
As long as this logic is encapsulated inside data parser and is opaque for your api users (i.e. they will always get a string) any approach is fine, e.g.:
- (NSString*)parseID:(NSDictionary*)message {
id rawID = message["myID"];
if ([rawID isKindOfClass:[NSString class]]){
return rawID;
} else if ([rawID isKindOfClass:[NSNumber class]]) {
return [(NSNumber*)rawID stringValue];
} else {
// We might still want to handle this case.
NSAssert(false, #"Unexpected id type");
return nil;
}
}
Alternative is to define stringValue in extension, so any possible objet will respond to selector:
#implementation NSString(JSONStringParsing)
- (NSString *)stringValue {
return [self copy];
}
#end
Why not just use description?
NSArray *objects = #[
#NSIntegerMin,
#NSIntegerMax,
#"123456789"
];
for (id object in objects) {
NSString *stringObject = [object description];
NSLog(#"%# -> %# | %#", [object className], [stringObject className], stringObject);
}
Any one please help me to understand the String comparison technique in Objective-C
NSString *strNew1 = #"AA";
NSString *strNew2 = #"AA";
So to compare both the strings we could use,
Method 1. if (strNew1 == strNew2) {
NSLog(#"Equal");
}
or
Method 2: if ([strNew1 isEqualToString:strNew2]) {
NSLog(#"Equal");
}
In this condition both of them are success. But am aware that method 1 will get failed at certain other condition. And also I have tried the below conditions(All are success).
NSString *strNew = #"AA";
NSString *strNew1 = #"AA";
NSString *strNew11 = [[NSString alloc] initWithString:strNew1];
NSString *strNew3 = strNew;
NSArray *arr = #[#"AA"];
NSString *strNew4 = [arr objectAtIndex:0];
NSString *strNew5 = [arr objectAtIndex:0];
_test = strNew5;
_test1 = #"AA";
if ([strNew isEqualToString:strNew1]) {
NSLog(#"Equal");
}
if (strNew == strNew3) {
NSLog(#"Equal1");
}
if (strNew == [arr objectAtIndex:0]){
NSLog(#"Equal2");
}
if (strNew == strNew4){
NSLog(#"Equal3");
}
if (strNew5 == strNew4){
NSLog(#"Equal4");
}
if (strNew4 == [arr objectAtIndex:0]){
NSLog(#"Equal5");
}
if (strNew11 == [arr objectAtIndex:0]){
NSLog(#"Equal11");
}
if (self.test == strNew4){
NSLog(#"Equal3");
}
if (self.test == self.test1){
NSLog(#"Equal3");
}
TEST *test = [TEST new]; // Tried with a class with NSString property with value "AA" . (test.strTest value is #"AA")
if (strNew == test.strTest) {
NSLog(#"Equal"); //success
}
I knew most of them are redundant. Am not able to understand the basics behind this. Please anyone give clear explanation on the concept behind this. Thanks.
In the cases you defined the strings created are internally treated as string literals. The runtime will not allocate different memory space to such strings.
Essentially all the strings that contain the same string literal ("AA" in your case) will point to the same memory location. This is done as a part of memory optimization by Apple.
When you change the value of any string (say to "AB") a new address will be allocated to that NSString object and then == will fail.
You need to use below instance method of NSString class.
- (BOOL)isEqualToString:(NSString *)aString;
So, In your case simply follow below:
if ([strNew isEqualToString strNew4]){
NSLog(#"Equal3");
}
By doing (strNew == strNew4),
You are only comparing the addresses of the objects.
The first way compares pointers, while the second way compares objects.
That is, the first way compares if the pointers have the same value. In this case it is likely that they don't, in the second case the objects will be compared. Since they are initialized the same way they could be equal. (Note, it appears that with the UIButton's implementation of isEqual: the result is always false.)
In most cases using == is not what you want. However, what is appropriate depends on your objective.
if (strNew1 == strNew2) //This compared your pointers
{
}
and
if ([strNew1 isEqualToString:strNew2]) //Compares NSString object
{
}
Remember that isEqualToString: comes with a WARNING
[string1 isEqualToString: string2]
will effectively return false is both strings are nil.
I am using the ActionSheetStringPicker from the ActionSheetPickers3.0 (since I no longer can use the old picker views because of iOS 8). This is how I am calling the method:
ActionSheetStringPicker *genderPicker = [[ActionSheetStringPicker alloc]
initWithTitle:#"Gender" rows:categoryTypes initialSelection:nil target:self
successAction:#selector(selectedGender:) cancelAction:#selector(cancelledGender)
origin:gender];
[genderPicker showActionSheetPicker];
My success action code is this:
-(void) selectedGender:(NSNumber *)genderSelected {
NSLog(#"selected gender: %#",genderSelected);
if (genderSelected == 0) {
NSLog(#"male");
gender.text = #"Male";
} else {
NSLog(#"female");
gender.text = #"Female";
}
}
I am getting either a 1 or 0 value from the selected gender (male/female) when I NSLog the genderSelected value. My problem is that in my if-statement it always says I picked female. I'm getting the correct value that I select from the picker, but can't seem to figure out what the problem is. Does anyone know how I can get my if-statement working? Thanks!
In your success callback method the parameter you are getting is of type NSNumber. You cannot directly compare the object of type NSNumber with int value 0. Therefore use the following :
if (genderSelected.intValue == 0) {
NSLog(#"male");
gender.text = #"Male";
} else {
NSLog(#"female");
gender.text = #"Female";
}
Well this isn't exactly what I was looking for, but it worked. I set the NSNumber that I was getting as an NSString then compared to a "0" and "1" string. Here is my solution:
-(void) selectedGender:(NSNumber *)genderSelected {
NSString *string = [NSString stringWithFormat:#"%#",genderSelected];
if ([string isEqualToString:#"0"]) {
NSLog(#"male");
} else if ([string isEqualToString:#"1"]) {
NSLog(#"female");
}
}
This question already has answers here:
How to detect if NSString is null?
(5 answers)
Closed 8 years ago.
I'm new to iOS development. I get an error when I compare NSString with NSString nil value. It is not working in if condition.
my code is:
NSDictionary *responseFromJSON = [JSON objectForKey:#"response"];
NSString *strResponseMsg = [responseFromJSON objectForKey:#"104"];
if ([strResponseMsg isEqualToString:nil])
{
NSLog(#"login Invalid");
}
else
{
NSLog(#"login success");
}
You can simply do like this,
NSString * string = nil;
if (string!=nil && // not nil, means 0x0 object
string.length>0 && // at leaset one character should exists
[string isEqual:[NSNull null]]) { // to avoid 'null' in string
// valid string
}
You can do like this,
if ([yourString isEqual:[NSNull null]])
{
//your code goes here
}
Hope this helps.
Use below
NSString *strResponseMsg = [responseFromJSON objectForKey:#"104"];
if (!strResponseMsg)
{
NSLog(#"login Invalid");
}
else
{
NSLog(#"login success");
}
If you want to check the NSString whether it's nil or empty.
You just need to do something like that:
if (strResponseMsg.length) {}
Because it will not go inside if the strResponseMsg is nil or empty. It will only go inside when strResponseMsg is not nil and no empty.
This question already has answers here:
Comparing Strings in Cocoa
(5 answers)
Closed 9 years ago.
What am I doing wrong with this conditional statement using a UILabel in Xcode?
Over simplified example, but I am trying to change the content of the UILabel in relation to text in the UILabel.
-(IBAction)answerQuestion:(id)sender{
NSString *startingLableContent = #"Do dogs bark?";
NSString *answer = #"Yes.";
NSString *askAnother = #"What else do you want?";
if (mainLable.text == startingLableContent) {
mainLable.text = answer;
}else if (mainLable.text == answer){
mainLable.text = askAnother;
}
}
You should compare them using isEqualToString
like this:
if ([mainLable.text isEqualToString:startingLableContent])
otherwise you are testing memory locations instead of content.
to compare Strings in Objective-C, use isEqualToString
-(IBAction)answerQuestion:(id)sender{
NSString *startingLableContent = #"Do dogs bark?";
NSString *answer = #"Yes.";
NSString *askAnother = #"What else do you want?";
if ([startingLableContent isEqualToString:mainLable.text]) {
mainLable.text = answer;
}else if ([answer isEqualToString:mainLable.text]){
mainLable.text = askAnother;
}
}
Try this:
if ([mainLable.text isEqualToString:startingLableContent]) {
// do stuff
}
==
It turns out that you can't just say if (someString == someOtherString). It will almost always return NO.
It has to do with some stuff about where the string is stored in memory. You can use == with int's and double's and those kind of things, but with NSString's, you need to do:
if ([mainLabel.text isEqualToString:someOtherString])
And so, your method should look like:
-(IBAction)answerQuestion:(id)sender{
NSString *startingLableContent = #"Do dogs bark?";
NSString *answer = #"Yes.";
NSString *askAnother = #"What else do you want?";
if ([mainLable.text isEqualToString:startingLableContent]) {
mainLable.text = answer;
}else if ([mainLable.text isEqualToString:answer]){
mainLable.text = askAnother;
}
}
You compare the pointers, not actual strings. If you want to compare strings, consider using isEqualToString instead.