How to check if NSString returned by objectForKey is "" objective c - 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:#""].

Related

Getting "Array element cannot be nil" from Analyzer as a false-positive

I have a case where the XCode analyzer is flagging valid code.
We have an NSString category with a method isEmpty which checks if the string is empty, including checking for a nil string. When it's used in combination with adding the string to an array, the analyzer complains:
if (![NSString isEmpty:myString]) {
[_myArray addObject:myString];
}
The analyzer will then complain with Array element cannot be nil, because it isn't smart enough to detect that isEmpty is preventing that.
What's the best workaround? I know I can change the condition to if (myString && ![NSString isEmpty... but that seems like a clunky workaround.
EDIT: By request, here's the body of isEmpty:
+ (BOOL)isEmpty:(NSString *)string
{
return (string ? [string isEqualToString:#""] : YES);
}
You're correct that you have to show the analyzer every possible logical path. Your "workaround" is perfectly good.
It might be that your isEmpty could be written to help the analyzer more, but you didn't show that, so it's impossible to say. Based on what you've actually shown, I would suggest that you just use your "workaround" and move on.
In Objective-C the easiest way to check for non-nil and non-empty for NSString is to get the length. It returns 0 for nil and empty and the proper length for non-empty.
NSString *testNil = nil;
NSString *testEmpty = #"";
NSString *testNonEmpty = #"Hello";
NSInteger testNilLength = [testNil length]; // -> 0
NSInteger testEmptyLength = [testEmpty length]; // -> 0
NSInteger testNonEmptyLength = [testNonEmpty length]; // -> 5

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!
}

String compare 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”.

Weird cocoa bug?

Hey folks, beneath is a piece of code i used for a school assignment.
Whenever I enter a word, with an O in it (which is a capital o), it fails!
Whenever there is one or more capital O's in this program, it returns false and logs : sentence not a palindrome.
A palindrome, for the people that dont know what a palindrome is, is a word that is the same read left from right, and backwards. (e.g. lol, kayak, reviver etc)
I found this bug when trying to check the 'oldest' palindrome ever found: SATOR AREPO TENET OPERA ROTAS.
When I change all the capital o's to lowercase o's, it works, and returns true.
Let me state clearly, with this piece of code ALL sentences/words with capital O's return false. A single capital o is enough to fail this program.
-(BOOL)testForPalindrome:(NSString *)s position:(NSInteger)pos {
NSString *string = s;
NSInteger position = pos;
NSInteger stringLength = [string length];
NSString *charOne = [string substringFromIndex:position];
charOne = [charOne substringToIndex:1];
NSString *charTwo = [string substringFromIndex:(stringLength - 1 - position)];
charTwo = [charTwo substringToIndex:1];
if(position > (stringLength / 2)) {
NSString *printableString = [NSString stringWithFormat:#"De following word or sentence is a palindrome: \n\n%#", string];
NSLog(#"%# is a palindrome.", string);
[textField setStringValue:printableString];
return YES;
}
if(charOne != charTwo) {
NSLog(#"%#, %#", charOne, charTwo);
NSLog(#"%i", position);
NSLog(#"%# is not a palindrome.", string);
return NO;
}
return [self testForPalindrome:string position:position+1];
}
So, is this some weird bug in Cocoa?
Or am I missing something?
B
This of course is not a bug in Cocoa, as you probably knew deep down inside.
Your compare method is causing this 'bug in Cocoa', you're comparing the addresses of charOne and charTwo. Instead you should compare the contents of the string with the isEqualToString message.
Use:
if(![charOne isEqualToString:charTwo]) {
Instead of:
if(charOne != charTwo) {
Edit: tested it in a test project and can confirm this is the problem.
Don't use charOne != charTwo
Instead use one of the NSString Compare Methods.
if ([charOne caseInsensitiveCompare:charTwo] != NSOrderedSame)
It may also have to do with localization (but I doubt it).

If else statment not work in my app

I´m making a dictionary (this is my test app)
here is my code which not work:
- (IBAction) btnClickMe_Clicked:(id)sender {
NSString *kw = s.text;
NSString *encodedkw = [kw stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *mms = [NSString stringWithFormat: #"%#", encodedkw];
if (mms=NULL){
iMessageLabel.text=#"put text";
} else if (mms=#"a"){
iMessageLabel.text=#"this is a";
} else if (mms=#"b"){
iMessageLabel.text=#"this is b";
}
}
anybody have some idea with this ?
thanks
ALex
You cannot use == on NSString objects. Try doing this:
if (encodedkw == nil){
iMessageLabel.text=#"put text";
} else if ([encodedkw isEqualToString:#"a"]){
iMessageLabel.text=#"this is a";
} else if ([encodedkw isEqualToString:#"b"]){
iMessageLabel.text=#"this is b";
}
mms should be equal to encodedkw so I switched to using that. Also I'm using isEqualToString for string comparison. Finally, I've changed the null check to check against nil instead of NULL.
You've used = rather than ==
May it happen, that you need to call some kind of string manipulation routine like compare to compare strings, not just comparing the pointers?
Besides mms=NIL means assignment NIL to mms not comparison desired.
Upd.: NIL does not mean empty string. You should write [mms length] == 0 instead to see if the string is empty.