NSString: isEqual vs. isEqualToString

Objective CIphoneCocoaNsstring

Objective C Problem Overview


What is the difference between isEqual: and isEqualToString:?

Why are classes adding isEqualTo* methods (isEqualToArray for NSArray, isEqualToData for NSData, ...) instead of just overriding isEqual: ?

Objective C Solutions


Solution 1 - Objective C

isEqual: compares a string to an object, and will return NO if the object is not a string. isEqualToString: is faster if you know both objects are strings, as the documentation states:

> Special Considerations > > When you know both objects are strings, this method is a faster way to check equality than isEqual:.

isEqualTo<Class> is used to provide specific checks for equality. For instance; isEqualToArray: checks that the arrays contain an equal number of objects, and that the objects at a given index return YES for the isEqual: test.

Solution 2 - Objective C

Also, for writing your own -isEqual: and -isEqualTo<Class>: methods, the convention is to allow nil arguments for -isEqual: and raise an exception for nil arguments to -isEqualTo<Class>:

Solution 3 - Objective C

Expanding on @Abizern and @Jonathan Dann answers, both isEqual and isEqualToString work with nil values.

- (void)testStringEqual {
    NSString *string = nil;

    STAssertFalse([string isEqual:@"test"], @"NSString isEqual");
    STAssertFalse([string isEqualToString:@"test"], @"NSString isEqualToString");

    // Note that these both return NO
    STAssertFalse([string isEqual:nil], @"NSString isEqual");
    STAssertFalse([string isEqualToString:nil], @"NSString isEqualToString");

    string = @"test";

    STAssertTrue([string isEqual:@"test"], @"NSString isEqual");
    STAssertTrue([string isEqualToString:@"test"], @"NSString isEqualToString");

    STAssertFalse([string isEqual:nil], @"NSString isEqual");
    STAssertFalse([string isEqualToString:nil], @"NSString isEqualToString");
}

Solution 4 - Objective C

My guess is that it provides a slight performance enhancement, as isEqualToString: won't have to type-check what's passed in.

Solution 5 - Objective C

I highly recommend this. The performance benefits of isEqualToString are basically negligible for most applications. But there are two other distinctions the author mentions:

  • Type safety
  • The way nil is handled

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJaka JančarView Question on Stackoverflow
Solution 1 - Objective CAbizernView Answer on Stackoverflow
Solution 2 - Objective CJonathan DannView Answer on Stackoverflow
Solution 3 - Objective CrespectTheCodeView Answer on Stackoverflow
Solution 4 - Objective CiKenndacView Answer on Stackoverflow
Solution 5 - Objective CBen PackardView Answer on Stackoverflow