Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding NSString comparison

Both the following comparisons evaluate to true:

1)

@"foo" == @"foo"; 

2)

NSString *myString1 = @"foo"; NSString *myString2 = @"foo"; myString1 == myString2; 

However, there are definitely times where two NSStrings cannot be compared using the equality operator, and [myString1 isEqualToString:myString2] is required instead. Can someone shed some light on this?

like image 938
Yarin Avatar asked Sep 13 '10 19:09

Yarin


People also ask

How can I compare two Nsstrings?

To compare two strings equality, use isEqualToString: . BOOL result = [firstString isEqualToString:secondString]; To compare with the empty string ( @"" ), better use length .

What does NSString mean?

A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior. iOS 2.0+ iPadOS 2.0+ macOS 10.0+ Mac Catalyst 13.0+ tvOS 9.0+ watchOS 2.0+

Do I need to release NSString?

If you create an object using a method that begins with init, new, copy, or mutableCopy, then you own that object and are responsible for releasing it (or autoreleasing it) when you're done with it. If you create an object using any other method, that object is autoreleased, and you don't need to release it.

How do I check if a string contains a substring in Objective C?

Checking the string contains another To check if a string contains another string in objective-c, we can use the rangeOfString: instance method where it returns the {NSNotFound, 0} if a 'searchString' is not found or empty (""). Output: string contains you!


1 Answers

The reason why == works is because of pointer comparison. When you define a constant NSString using @"", the compiler uniquifies the reference. When the same constants are defined in other places in your code, they will all point to the same actual location in memory.

When comparing NSString instances, you should use the isEqualToString: method:

NSString *myString1 = @"foo"; NSString *myString2 = @"foo"; NSString *myString3 = [[NSString alloc] initWithString:@"foo"]; NSLog(@"%d", (myString2 == myString3))  //0 NSLog(@"%d", (myString1 == myString2)); //1 NSLog(@"%d", [myString1 isEqualToString:myString2]); //1 NSLog(@"%d", [myString1 isEqualToString:myString3]); //1 [myString3 release]; 

Edit:

NSString *myString3 = [[NSString alloc] initWithString:@"foo"];  // this is same with @"foo" 

initWithString: does not create a new reference any more, you will need initWithFormat,

NSString *myString3 = [[NSString alloc] initWithFormat:@"foo"]; 
like image 191
Jacob Relkin Avatar answered Sep 21 '22 22:09

Jacob Relkin