Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
757 views
in Technique[技术] by (71.8m points)

objective c - What is the NSObject isEqual: and hash default function?

I have a database model class that is a NSObject. I have a set of these objects in a NSMutableArray. I use indexOfObject: to find a match. Problem is the model object's memory address changes. So I am overriding the hash method to return the model's row ID. This however does not fix it. I also have to override the isEqual: method to compare the value of the hash method.

What does the isEqual: method use to determine equality by default?

I'm assuming it uses the memory address. After reading the isEqual: documentation I thought it used the value from the hash method. Obviously, that is not the case as my attempt to override that value did not solve my initial problem.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As you've correctly guessed, NSObject's default isEqual: behaviour is comparing the memory address of the object. Strangely, this is not presently documented in the NSObject Class Reference, but it is documented in the Introspection documentation, which states:

The default NSObject implementation of isEqual: simply checks for pointer equality.

Of course, as you are doubtless aware, subclasses of NSObject can override isEqual: to behave differently. For example, NSString's isEqual: method, when passed another NSString, will first check the address and then check for an exact literal match between the strings.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...