当前位置: 动力学知识库 > 问答 > 编程问答 >

objective c - Comparing nil properties in isEqual

问题描述:

EDIT

From the initial answers, I wasn't clear enough. I just want to check equality between objects of my own custom class, with the result dependent on its properties (pretty standard I believe)? The bit I'm struggling with is making sure a property is treated as equal when both instances have nil for that property.

END EDIT

I want objects of my custom class to return YES for isEqual whenever all of its properties are the same as those of the object passed as the argument. This should include when both properties are nil. I recently learned that [nil isEqual:nil] returns NO.

Will the below implementation achieve what I am looking for?

- (BOOL)isEqual:(id)object

{

if (object == self)

return YES;

if (!object || ![object isKindOfClass:[self class]])

return NO;

return (

(!object.numberProperty && !self.numberProperty) || (object.numberProperty && self.numberProperty && [object.numberProperty isEqualToNumber:self.numberProperty])

&&

(!object.stringProperty && !self.stringProperty) || object.stringProperty && self.stringProperty && [object.stringProperty isEqualToNumber:self.stringProperty])

...etc

);

}

I am trying to return YES when both properties are nil and also avoid sending isEqualToNumber or isEqualToString to nil.

For BOOLs I would guess that this is not necessary since a BOOL can't be nil - will a simple == suffice for booleans?

Anything I'm missing, or any ways to improve this?

网友答案:

Since you can't (ok, it's just not a good idea) override isEquals for all object types including nil, the obvious choice is to just make a separate simple function for the times you need it;

BOOL nilEqual(id a, id b)
{
    return (a == nil && b == nil) || [a isEqual:b];
}
网友答案:

nil cannot call isEqual since it is... well nil. It would not know which isEqual to call. It is not an object. I do not know of a way to do this and doubt there is away (someone please correct me, I would love to see an implementation for this).

That being said, normally you need to check for nil pointers before calling isEqual so:

if ((!someObject && !otherObject) || [someObject isEqual:otherObject]);

This would give you what you want and you could easily create a block (or maybe a macro) so you would not have to type out this out every time.

网友答案:

Looks like I found a little bit simpler and more optimized solution than http://stackoverflow.com/a/18033891/440168:

BOOL nilEqual(id a, id b)
{
    return (a == b) || [a isEqual:b];
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: