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开发者_Go百科, 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!
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.
With objects, the ==
operator tests for pointer equality. That is, the two variables are the same if the pointers both point to the same object. The string fetched from the URL is not the same object as the constant string, so it fails. You want to use NSString's isEqualToString:
method, which tests for whether the strings themselves are equal rather than the pointers.
You can try to compare with a isEqualToString method
精彩评论