iphoneobjective-cxcodensstringinitwithcontentsofurl

What is the difference between NSString = @"HELLO" and NSString getting that same string using initWithContentsOfURL


I have a string that is getting the content from URL and when I try to use it, it doesn't work the way I thought it should.

When I initialize NSString with with contents of URL like this:

NSString *strFromURL = [[NSString alloc] initWithContentsOfURL:someURLReturningTextHELLO encoding:NSUTF8StringEncoding error:nil];
NSLog(@"%@",strFromURL); // returns "HELLO" // as expected

but when I try:

if (strFromURL == @"HELLO") { NSLog(@"IT WORKS"); } // This doesn't happen

When I do the same process with:

NSString *mySimpleString = @"HELLO";
if (mySimpleString == @"HELLO") { NSLog(@"IT WORKS"); } // This works

So, my question is, how can I get content from URL that I can use later in my IF statement?

*I'm new to Objective-C. Thanks!


Solution

  • When you asking for if (strFromURL == @"HELLO") you're comparing equality of objects, but not strings. When you call comparison of two constant strings it works, other it fails whether strings in compared objects are equal or not.

    Call if ([strFromURL isEqualToString:@"HELLO"]) instead.