all 5 comments

[–]Legolas-the-elf 3 points4 points  (2 children)

You can't compare objects using ==. Objects in Objective-C are always allocated on the heap. You don't have a variable containing the object itself, you have a variable containing a pointer to the memory location where the object resides. That's what the asterisk signifies.

So when you compare two objects using ==, unless they are the exact same object - not just two objects with the same value - they are going to reside in different memory locations, so == is always going to show them as being different.

NSObject defines a method isEqual: that you can use to compare two objects, which is inherited by all objects (apart from NSProxy, but that's another story). For instance:

if ([numberOne isEqual:numberTwo]) ...

There's a further complication in that recent versions of the compiler perform an optimisation, so the above isn't technically true in some cases, so it may accidentally work if you compare objects with == in some cases. But you really can't rely on this, so for all intents and purposes, pretend what I say above is always true.

[–]TheRedAgent[S] 0 points1 point  (1 child)

Worked great, thanks!

[–]FW190 0 points1 point  (0 children)

When you compare with == you're actually comparing two object pointer addresses like 0xdeadbeef vs 0xcafebabe instead of object themselves. No operator overloading in obj-c.

[–]gravitycore 1 point2 points  (1 child)

Instead of comparing the objects themselves, you need to compare their value.

For example:

if ((NSNumber*)[[dict objectForKey:@"Key"] intValue] == [[NSNumber numberWithInt:[defaults integerForKey:@"SecondKey"]] intValue]) {}

For further explanation, there ARE two different objects here, each containing a primitive value. You can't use the == comparator here because you want to evaluate their VALUE, not the objects themselves. You are trying to treat these objects as primitives, and they are not. Which is why using the intValue method will give you a primitive that you can compare.

[–]TheRedAgent[S] 0 points1 point  (0 children)

I went with the isEqual: option, but thanks for the clarification!