-2

I have a method which parses HTML. In there there is an if/else statement:

if ((NSNumber1 == NSNumber2)) {
    NSLog(@"dafuq1?");
} else {
    NSLog(@"dafuq2?");
}

The log is sometimes like this:

...:dafuq1?

...:dafuq2?

So both parts are called. But other times just one of them gets called! Why?

Btw. iOS 7.0.4, Xcode 5.0.1

And (NSNumber1 == NSNumber2) is true

Lorenzo B
  • 33,216
  • 24
  • 116
  • 190
gallileo
  • 462
  • 5
  • 21

1 Answers1

6

These are objects. You can't use == to compare equality. Use isEqualToNumber:.

if ([NSNumber1 isEqualToNumber:NSNumber2])
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Unless you want to see if they're the same object. – TotoroTotoro Nov 15 '13 at 17:33
  • @BlackRider Of course. But that isn't the case here. – rmaddy Nov 15 '13 at 17:34
  • 3
    @BlackRider As well, comparing `NSNumber` instances for pointer equality is a sure fire way to create baffling bugs. On some platforms, the numbers from -2 to 11 are shared instances. On other platforms, tagged pointers means that -2^55..2^55 (or ^56?) will be effectively shared instances (though they aren't actually backed by allocations at all). – bbum Nov 15 '13 at 17:46
  • @bbum thanks for the great clarification! – TotoroTotoro Nov 15 '13 at 17:55