98

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: ?

TheNeil
  • 3,321
  • 2
  • 27
  • 52
Jaka Jančar
  • 11,386
  • 9
  • 53
  • 74

5 Answers5

107

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.

Pang
  • 9,564
  • 146
  • 81
  • 122
Abizern
  • 146,289
  • 39
  • 203
  • 257
  • 3
    If you believe Aaron Hillegass then there is no performance difference, only a bit of type safty: http://blog.bignerdranch.com/334-isequal-vs-isequaltostring/ – Caro Dec 25 '13 at 18:47
  • 2
    Thanks for the link - useful. Although you're asking us to believe Mark Dalrymple - who I do :) – Abizern Jan 11 '14 at 17:24
  • Updated link: https://www.bignerdranch.com/blog/isequal-vs-isequaltostring/ – Max Mar 05 '19 at 21:35
17

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>:

Jonathan Dann
  • 280
  • 1
  • 7
7

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");
}
respectTheCode
  • 42,348
  • 18
  • 73
  • 86
5

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

iKenndac
  • 18,730
  • 3
  • 35
  • 51
4

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
Ben Packard
  • 26,102
  • 25
  • 102
  • 183