String compare Objective-C - objective-c

I've been struggling with a simple comparison but I can't get it to work.
I´m reading a XML file and I need to compare data from it in order to show the right picture.
http://www.cleaner.se/larm.xml (Example file for parsing)
I have tried things like:
if([aLarm.larmClass isEqualToString:#"A"])
NSLog(#"same");
else
NSLog(#"Not same");
If I use: NSLog(aLarm.larmClass); console puts it out nicely as it should. What am I doing wrong?

You can use the NSString compare: methods. For example:
if ([myString caseInsensitiveCompare:#"A"] == NSOrderedSame ) {
NSLog(#"The same");
} else {
NSLog(#"Not the same.");
}
The result is an NSComparisonResult which is just an enum with types NSOrderedSame, NSOrderedAscending and NSOrderedDescending.
Check the documentation on the various compare: methods here.
Of course, if the receiver is actually an NSString, then isEqualToString: should also work. So if you're trying to compare a class name (aLarm.larmClass ??), then you can call:
if ([NSStringFromClass([aLarm class]) isEqualToString:#"A"] ) {
NSLog(#"The same");
}

If the larmClass property is a string, make sure that it is actually one character in length (i.e. it doesn't have any leading or trailing whitespace that was accidentally included when parsing the XML). If the larmClass property truly is an NSString containing the letter ‘A’ then [aLarm.larmClass isEqualToString:#"A"] will return YES.
Do a:
NSLog(#"%u, %#", [aLarm.larmClass length], aLarm.larmClass);
and just make sure that it shows “1, A”.

Related

How to check if NSString returned by objectForKey is "" objective c

I'm not exactly sure how to check whether a NSString is blank or not, I've got this code...
NSString *imageName = [myItem objectForKey:#"iconName"];
if(imageName == #"")
{
}
And when I do a print on the myItem object, it comes up as..
iconName = "";
At the NSString *imageName line, I noticed in xcode in the console it says
"variable is not NSString"
Which I don't get as iconName is saved and stored on the parse.com database as a NSString.
When I run that code though it doesn't seem to realise that imageName = "";
You should use this code block when comparing strings:
if ([imageName isEqualToString:#""]){
}
You need to use isEqualToString to compare two strings. If you just use == then you are comparing two pointers.
You could also check to see if the object you are receiving is a NSString by:
if ([imageName isKindOfClass:[NSString class]])
Hope this helps.
Although you have a few answers already, here is my take.
First of all, your warning (not error) can be fixed like this:
NSString *imageName = (NSString *)[myItem objectForKey:#"iconName"];
Then, I would check to make sure that the string is not nil and that it is not blank. The easiest way to do this in objective-C is to check the length of the string, since if it nil it will return 0, and if it is empty, it will return 0:
if([imageName length] == 0)
{
// This is an empty string.
}
As #jlehr points out, if there is the possibility that imageName may not actually be stored as a string, then in order to prevent a crash you need to check first. (This may or may not be needed, depending on the logic of your application):
if ([imageName isKindOfClass:[NSString class]]
{
if([imageName length] == 0)
{
// This is an empty string.
}
}
The "variable is not NSString" is probably because objectForKey: return an id.
To should use [imageName isEqualToString:#""].

Objective-C string comparison

I have an array of names but can't seem to make the comparison work. Do I have an improper use of the language here?
NSLog(#"%#",[arrayOfNames objectAtIndex:0]);
if ([arrayOfNames objectAtIndex:0] == "Blue"){
NSLog(#"it's Blue");
}
else {
NSLog(#"it's not Blue");
}
The output is the following one:
Blue
it's not Blue
Use the following:
if ([[arrayOfNames objectAtIndex:0] isEqualToString:#"Blue"])
You're comparing two objects (one of the id-type, the other is a C-string) with the == operator. The comparison will fail, since they are 2 different objects. With the isEqualToString you are comparing the value of the object to the string #"Blue".

How to best compare two NSString objects while ignoring case?

I want to compare two strings. It fails when the string have capital letter. How do I convert both string to capitalize and compare.
I have a sample code, can someone correct this.
if ([[txtAnswer.text capitalizedString] isEqualToString:[answer capitalizedString]]) {
// Do somehing
}
If you look at the NSString class reference you will see under the heading Identifying and Comparing Strings the methods caseInsensitiveCompare: and localizedCaseInsensitiveCompare:.
You might try something like:
if ([txtAnswer.text caseInsensitiveCompare: answer] == NSOrderedSame) {
// do something.
}
You can do a case insensitive string compare.
if([txtAnswer.text compare:answer options:NSCaseInsensitiveSearch] == NSOrderedSame)
{
// Do somehing
}

Check if property of object instance is 'blank'

I am trying to implement the code below without success. Basically, I want to set the display name to use thisPhoto.userFullName if it is not 'Blank", else show thisPhoto.userName instead.
UILabel *thisUserNameLabel = (UILabel *)[cell.contentView viewWithTag:kUserNameValueTag];
NSLog(#"user full name %#",thisPhoto.userFullName);
NSLog(#"user name %#",thisPhoto.userName);
if (thisPhoto.userFullName && ![thisPhoto.userFullName isEqual:[NSNull null]] )
{
thisUserNameLabel.text = [NSString stringWithFormat:#"%#",thisPhoto.userFullName];
}
else if (thisPhoto.userFullName == #"")
{
thisUserNameLabel.text = [NSString stringWithFormat:#"%#",thisPhoto.userName];
}
Currently, even if userFullName is blank, my userName is still not displayed on the screen.
I'd prefer
if([thisPhoto.userFullName length])
Use -length. This will be 0 whenever the string is nil or the empty string #"". You generally want to treat both cases identically.
NSString *fullName = [thisPhoto userFullName];
thisUserNameLabel.text = [fullName length]? fullName : [thisPhoto userName];
I see a few points here
First - if your userFullName instance variable is NSString* then doing simple comparison with nil is enough:
if (thisPhoto.userFullName)
Unless, of course, you explicitly set it to be [NSNull null], which then requires the condition you wrote.
Second - comparing strings is done with isEqualToString: method so second condition should be rewritten as:
if ([thisPhoto.userFullName isEqualToString:#""]) {
...
}
Third - there's logic flaw - If your userFullName IS equal to empty string (#"") the code would still fall to the first branch. I.e. empty string (#"") is not equal to [NSNull null] or simple nil. Hence you should write to branches - one to handle empty string and nil, other one for normal value. So with a bit of refactoring your code becomes like this:
thisUserNameLabel.text = [NSString stringWithFormat:#"%#",thisPhoto.userFullName];
if (!thisPhoto.userFullName || [thisPhoto.userFullName isEqualToString:#""]) {
// do the empty string dance in case of empty userFullName.
}
If, as I suppose, thisPhoto.userFullName is a NSString you may try
[thisPhoto.userFullName isEqualToString:#""]
The other two answers are correct, and beat me to it. Rather than just repeat what they have said - I'll point out something else.
[NSNull null] is used to store nil values in collection classes (NSArray, NSSet, NSDictionary) that don't allow nil values to be stored in them.
So unless you're checking values that you get from a collection - there is no point checking against [NSNull null]
// this assumes userFullName and userName are strings and that userName is not nil
thisUserNameLabel.text = [thisPhoto.userFullName length] > 0 ? thisPhoto.userFullName : thisPhoto.userName;
"Blank" means #"", but also #" " or #"\n". So I would trim userFullName and check the length of that string.
if ([[thisPhoto.userFullName stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0) {
// it's blank!
}

How to write a valid boolean conditional in objective-c using objectForKey

I'm seeking to understand why the following always hits the ELSE clause. What I can't figure out is that regardless of the actual value ( NSLog shows a 0 or 1) this always hits the else. Any reason why?
The item NSArray is pulled from a JSON object -fyi
BOOL* instock = [item objectForKey:#"itemInStock"];
obj.instock = instock;
NSLog(#"and it was %#", obj.instock);
if (obj.instock == YES) {
//do yes stuff
}else {
//do no stuff
}
Your code here is rather strange. What is the type of obj.instock? Your very first line
BOOL* instock = [item objectForKey:#"itemInStock"];
makes no sense at all. -objectForKey: doesn't return BOOL* values. It returns id. I'm guessing here that you're actually getting an NSNumber * back, and it just happens to work alright because an NSNumber * fits inside of a BOOL * (as they are both pointers). Similarly, obj.instock is likely to be an NSNumber* as well (if it wasn't an object of some sort, your NSLog() would crash).
So, assuming that obj.instock is an NSNumber*, the conditional you want is simply
if ([obj.instock boolValue]) {
// yes
} else {
// no
}
You should also fix this code to not try and claim you have a BOOL* when you don't.
In your NSLog, you are using %#.
%# refers to objects. Contrary to your BOOL* instock which is not an object.
There are ways to fix that.
What data type does your [item objectForKey:#"itemInStock"]; return?
If it returns an NSNumber for example, then you can do:
obj.instock = [[item objectForKey:#"itemInStock"] boolValue];
NSLog(#"and it was %d", obj.instock);
if (obj.instock == YES) {
//do yes stuff
}else {
//do no stuff
}
Again, there are other ways to do that.