How to compare NSString with NSString nil Value? [duplicate] - ios

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.

Related

Check if contain Null

When I print the following I get (null)
NSLog(#"%#", [[responseObject objectAtIndex:i] objectForKey:#"child"]);
Now I want to do a validation to check if it returns (null). How am I supposed to do this?
I tried the following but it doesn't work:
1.
if (![[[responseObject objectAtIndex:i] objectForKey:#"child"] isEqualToString:#"(null)"]) {
}
2.
if (![[[responseObject objectAtIndex:i] objectForKey:#"child"] isEqual:#"(null)"]) {
}
"null" isn't just a NSString. You should do some research into the concept of a null object.
What you're looking for can be written like this:
if (![[responseObject objectAtIndex:i] objectForKey:#"child"]) {
//key "child" not in dictionary
}
(null) is the representation of nil displayed by NSLog.
You can write the following:
if ([[responseObject objectAtIndex:i] objectForKey:#"child"] == nil) {
}
Or a shorter alternative:
if (![[responseObject objectAtIndex:i] objectForKey:#"child"]) {
}
Another way to check is to use string length. I know other answers are just as good, I am just giving OP and anyone else in future some more options.
NSString *childStr = [[responseObject objectAtIndex:i]objectForKey:#"child"];
if ([childStr length] < 1)
{
//no value specified - childStr is NULL
}
else
{
//there is something in the childStr - throw a party!
}
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:#"hello"]) {
NSLog(#"only if not null show %#",[defaults objectForKey:#"hello"]);
}
This is a way to check it from User Defaults. It will only print if the saved object does not equal null.

Sign Up + Confirmation Password iOS [duplicate]

This question already has answers here:
Understanding NSString comparison
(7 answers)
Closed 7 years ago.
I´m trying to make a registration form. There are two UITextField to write the Password and to confirm it. When i write exactly the same password, it always shows: "Passwords do not match ".
-(IBAction)signUp:(id)sender{
#try {
if([[name text] isEqualToString:#""] || [[mail text] isEqualToString:#""] || [[phone text] isEqualToString:#""] || [[password text] isEqualToString:#""] || [[rpassword text] isEqualToString:#""] ) {
[self alertStatus:#"Please check every field" :#"¡Alert!"];
}else if (password.text!=rpassword.text){
[self alertStatus:#"Passwords do not match " :#"¡Please Check!"];
}else {
NSString *strURL = [NSString stringWithFormat:#"http://miwebsite.com/signup.php?var1=%#&var2=%#&var3=%#&var4=%#", name.text, mail.text, phone.text, password.text];
NSURL *url2 = [NSURL URLWithString:strURL];
NSLog(#"url: %#", url2);
NSError *error;
NSData *dataURL = [NSData dataWithContentsOfURL:url2 options:0 error:&error];
if (dataURL == nil) {
NSLog(#"error: %#", error);
}
else {
NSLog(#"dataURL: %#", dataURL);
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
// THE REST OF THE CODE GOES HERE...
}
}
} #catch (NSException * e) {
NSLog(#"Exception: %#", e);
[self alertStatus:#"Sorry." :#"Failed"];
}
}
I used the debugger. password.text and rpassword.text are exactly the same word. ¿Why my code goes inside that sentence?
Thanks in advanced.
== in objective C is a pointer comparison instead of the content comparison. The text NSString object have 2 different memory address or pointers associated to them and although the content is same the memory they point is different and hence the statement inside this
else if (password.text!=rpassword.text){
[self alertStatus:#"Passwords do not match " :#"¡Please Check!"];
}
is executed. The pointers are different.
What you need is string comparison by doing so:
else if (![password.text.isEqualToString:rpassword.text]){
[self alertStatus:#"Passwords do not match " :#"¡Please Check!"];
}
For more explanation please check this link:
Understanding NSString comparison

Substring of NSString is not found [duplicate]

This question already has answers here:
NSString question - rangeOfString method
(2 answers)
Closed 8 years ago.
I'd like to check if this string contains "gif" value inside. I'm trying to achive this goal doing this:
NSString *originalSourceLinkToContent = #"site_media/obrazki/2014/07/faa4f4da470d7650cffe88f70cde230b_cropped.gif?1404832"
NSRange isRange = [originalSourceLinkToContent rangeOfString:#"cropped"; options:NSCaseInsensitiveSearch];
if(isRange.location != 0) {
//found it...
NSLog(#"HAS STRING");
} else {
NSLog(#"HAS NO STRING");
}
where originalSourceLinkToContent is my string. I always get "HAS NO STRING" message even if there is this substring. How to make it working? In android it is simple because there is a method for that and always woks. What is equivalent method in iOS?
Use NSNotFound instead of 0
NSString *str2 = #"site_media/obrazki/2014/07/faa4f4da470d7650cffe88f70cde230b_cropped.gif?1404832";
NSRange isRange = [str2 rangeOfString:#"cropped" options:NSCaseInsensitiveSearch];
//use `NSNotFound`
if(isRange.location != NSNotFound) {
//found it...
NSLog(#"HAS STRING");
} else {
NSLog(#"HAS NO STRING");
}
This code will work

Check if JSON value exists - iOS

I have an iOS application which downloads and parses a Twitter JSON feed and then presents that feed in a UITableView. This all works fine but I have one question:
When the user taps a UITableView cell, the app will look into the array "tweets_links" and see if that particular tweet has an attached URL, if it does then the web view will appear.
Because not all tweets have website URLs, I have added a simple try catch statement (like in C++) which can tell me if there is an exception when trying to access that part of the array.
My question is: is this is good or bad approach to doing this??
Here is my code:
int storyIndex = indexPath.row;
int url_test = 1;
NSString *url;
#try {
url = [[tweets_links[storyIndex] valueForKey:#"url"] objectAtIndex:0];
}
#catch (NSException *problem) {
// There is NO URL to access for this Tweet. Therefore we get the out of bounds error.
// We will NOT take the user to the web browser page.
// Uncomment the line below if you wish to see the out of bounds exception.
// NSLog(#"%#", problem);
url_test = 0;
}
if (url_test == 1) {
WebBrowser *screen = [[WebBrowser alloc] initWithNibName:nil bundle:nil];
self.seconddata = screen;
seconddata.web_url = url;
screen.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentViewController:screen animated:YES completion:nil];
}
else if (url_test == 0) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Info" message:#"There is no URL attatched to this Tweet." delegate:self cancelButtonTitle:#"Dismiss" otherButtonTitles:nil];
[alertView show];
[tweetTableView deselectRowAtIndexPath:indexPath animated:YES];
}
Is there a much better way of trying to achieve what I am doing???
Thanks, Dan.
Using try and catch is Objective-C isn't encouraged there are other ways checking and handling errors
// firstObject will return the first object in the array or nil if the array is empty.
url = [[tweets_links[storyIndex][#"url"]] firstObject];
if (!url) {
// handle the case for no url
} else {
// do something with url
}
Since sending a message to nil is safe in Objective-C and returns nil it's safe to chain calls. e.g. If the dictionary didn't have an object for that key, then it would return nil and sending firstObject to nil returns nil.
Using either if the below approaches will be fine because TRY CATCH is used to catch programming errors
and use
objectForKey:
instead of
valueForKey:
if ([tweets_links[storyIndex] objectForKey:#"url"] != nil)
OR
if ([url isKindOfClass:[NSString class]])
{
// Code handling the URL
}
else
{
// Code handling there is no URL
}
I don't know a ton about the Twitter feed, but you can probably check for a nil value returned from objectForKey: like so
if ([tweets_links[storyIndex] objectForKey:#"url"] != nil) { /* process the URL */ }
Your code assumes that the value is always an array of at least size = 1, it would be safer to inspect the #"url" key's value before assuming it's an array.
Using exceptions in Objective-C is throwned upon. Exceptions are reserved for programming errors. You don't catch them, you fix the code. With a JSON document, you never have any guarantees what you received, so just be careful.
NSString* url = nil;
NSArray* linksArray = nil;
NSDictionary* linkDict = nil;
NSArray* urlArray = nil;
if ([tweet_links isKindOfClass:[NSArray class]])
linksArray = tweet_links;
if (storyIndex >= 0 && storyIndex < linksArray.count)
linkDict = linksArray [storyIndex];
urlArray = linkDict [#"url"];
if ([urlArray isKindOfClass:[NSArray class]] && urlArray.count > 0)
url = urlArray [0];
if ([url isKindOfClass:[NSString class]])
{
// Code handling the URL
}
else
{
// Code handling there is no URL
}
Note that sending messages to a nil object always returns 0 / NO / nil as appropriate.
And please get into the habit of naming variables properly. You wrote "int url_test = 1;". What does url_test mean? I read the variable name, I have no idea what it means. I need to understand all the code. Making it "int" means it could be 0, 1, 2, 20000 or whatever. If you write instead "BOOL urlValid = YES;" that is clear: It means that you have a valid URL.
Since url value is a NSString value, you could use length to check both if it's nil and if not, if it has any value (not empty string). You can check then if this NSString is a valid url.
- (BOOL) validateUrl: (NSString *) candidate {
NSString *urlRegEx = #"(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+";
NSPredicate *urlTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", urlRegEx];
return [urlTest evaluateWithObject:candidate];
}
....
NSString *url = [[tweets_links[storyIndex][#"url"]] firstObject];
if ([url length] && [self validateUrl: url]) {
// Has a valid URL
}

NSNull isEqualToString: unrecognized selector on ObjC

Well my code was like this:
I have two strings, place and date. I am using them like this:
cell.datePlace.text= [NSString stringWithFormat:#"%#, %#",date,place];
In some entries, the output is like this:
"21/10/2012, <null>"
"21/11/2012, None"
"21/12/2013, London"
My app does not crash but I want the place to be visible only when is not null and not equal to None.
So I tried this:
NSString * place=[photo objectForKey:#"place"];
if ([place isEqualToString:#"None"]) {
cell.datePlace.text= [NSString stringWithFormat:#"%#",date];
} else {
cell.datePlace.text= [NSString stringWithFormat:#"%#, %#",date,place];
}
Problem was when place was <null> my app crashed and I got this error:
[NSNull isEqualToString:] unrecognized selector send to instance
So, i tried this:
if (place) {
if ([place isEqualToString:#"None"]) {
cell.datePlace.text= [NSString stringWithFormat:#"%#",date];
} else {
cell.datePlace.text= [NSString stringWithFormat:#"%#, %#",date,place];
}
} else {
cell.datePlace.text= [NSString stringWithFormat:#"%#",date];
}
But the problem remains.
I guess your source data is coming from JSON or similar (something where data is being parsed in and missing data is being set to NSNull). It's the NSNull that you need to deal with and aren't currently.
Basically:
if (place == nil || [place isEqual:[NSNull null]]) {
// handle the place not being available
} else {
// handle the place being available
}
Use
if (! [place isKindOfClass:[NSNull class]) {
...
}
instead of
if (place) {
...
}
Note: NSNull object is not nil, so the if (place) will be true then.
Use [NSNull null]:
if ([place isKindOfClass:[NSNull class]])
{
// What happen if place is null
}

Resources