使用不等运算符比较对象

Using an inequality operator to compare objects

在这里使用 != 对我来说似乎是错误的。我们正在比较对象,所以 isEqual 应该是正确的方法吗?

除非 NSNull null returns 具有一致内存地址的单例 ?

if ([super actionForLayer:layer forKey:@"backgroundColor"] != [NSNull null]) {
// whatever
}

Nick Lockwood 在他的要点中使用了这个 here 顺便说一句,读起来很酷

除非在 class 中覆盖了 isEqual,== 和 isEqual 之间没有区别。

== 运算符检查两个指针​​是否指向相同的对象,而 isEqual 检查对象的内容是否相同,但两个对象指针可能不指向相同的地址。

NSString *s1 = [NSString stringWithFormat:@"Hello"];
NSString *s2 = s1;
NSString *s3 = [NSString stringWithFormat:@"Hello"];

if (s1 == s2)
    NSLog(@"result 1");

if (s2 == s3)
    NSLog(@"result 2");

if ([s1 isEqual:s2])
    NSLog(@"result 3");

if ([s2 isEqual:s3])
    NSLog(@"result 4");

if (!([s2 isEqual:s3])) //Not equal for objects (change value to see)
    NSLog(@"result 5");

//prints pointer addresses
NSLog(@"%p", s1);
NSLog(@"%p", s2);
NSLog(@"%p", s3);