I have an array of current animal objects that can be viewed by day - for example, monday will return all animals that are available on a monday, etc.
I also have an array of saved animal objects.
How do I ensure that the saved animals don't show up in the current animals list?
Something like, if the currentAnimal.name isEqual to savedAnimal.name?
I need the objects in both arrays so it is important to compare the .name properties, I think?
Override isEqual and hash to do a comparison on the name if that is what you consider to make the objects 'equal'.
- (BOOL)isEqual:(id)other {
if (other == self)
return YES;
if (!other || ![other isKindOfClass:[self class]])
return NO;
return [((MyObject *)other).name isEqualToString:name];
}
and
- (NSUInteger)hash {
return [name hash];
}
You should use isEqual method if you want objects strictly equals or method isKindOfClass.
Look at NSObject reference
Related
I'm trying to draw an MTKMesh. To do this, I will need to set bind vertex buffers before executing the draw call. The documentation for MTKMesh.vertexBuffers is as follows:
/**
#property vertexBuffers
#abstract Array of buffers in which mesh vertex data resides.
#discussion This is filled with mesh buffer objects using the layout described by the vertexDescriptor property.
Elements in this array can be [NSNull null] if the vertexDescriptor does not specify elements for buffer for the given index
*/
open var vertexBuffers: [MTKMeshBuffer] { get }
So my understanding is that I need to iterate over this array, and bind a vertex buffer for every non-null element. I have this code so far:
for (bufferIndex, vertexBuffer) in mesh.vertexBuffers.enumerated() {
if (!(vertexBuffer is NSNull)) {
renderEncoder.setVertexBuffer(vertexBuffer.buffer, offset: vertexBuffer.offset, index: bufferIndex)
}
}
However, it doesn't seem to work as I get the following warning:
Cast from 'MTKMeshBuffer' to unrelated type 'NSNull' always fails
I also tried this:
if (vertexBuffer != nil) {
renderEncoder.setVertexBuffer(vertexBuffer.buffer, offset: vertexBuffer.offset, index: bufferIndex)
}
But this also doesn't seem to work work, as I get the warning:
Comparing non-optional value of type 'MTKMeshBuffer' to 'nil' always returns true
How can I iterate over the non-null elements of this array?
class MTKMeshBuffer is a subclass of NSObject. Apparently the declaration
open var vertexBuffers: [MTKMeshBuffer] { get }
is “lying” – the array elements can be pointers to MTKMeshBuffer instances or to NSNull instances. That is no problem in Objective-C because one can freely cast between different types of object pointers, and something like
for (MTKMeshBuffer *vertexBuffer in mesh.vertexBuffers) {
if (![vertexBuffer isKindOfClass:[NSNull class]]) {
//
}
}
compiles without warnings in Objective-C.
The Swift compiler does not accept this “lie” so easily: You have to cast the MTKMeshBuffer pointer to a NSObject pointer (the common superclass of MTKMeshBuffer and NSNull) before you can test for the actual type:
for (bufferIndex, vertexBuffer) in vertexBuffers.enumerated() {
if !(vertexBuffer as NSObject is NSNull) {
// ...
}
}
Alternatively one can use the Objective-C isKindOfClass method, which is imported to Swift as isKind(of:):
for (bufferIndex, vertexBuffer) in vertexBuffers.enumerated() {
if !vertexBuffer.isKind(of: NSNull.self) {
// ...
}
}
I am checking if an object I am getting back from the NSURLConnectionDataDelegate is the same object that I originally created. What I have been doing is:
// TESTING TO SEE IF THE RETURNED OBJECT IS THE SAME ONE I CREATED
if(connection == [self connectionPartial]) {
But was just curious is this is the same as doing:
if([connection isEqual:[self connectionPartial]]) {
It's not the same.
if(connection == [self connectionPartial]) {
This compares the address of the objects, eg. if the pointers point to the same instance.
if([connection isEqual:[self connectionPartial]]) {
This compares the contents of the objects. For instance for two separate NSString instances, this will return YES as long as the string content is the same:
NSString *s1 = #"Something";
NSString *s2 = #"Something";
BOOL sameInstances = (s1 == s2); // will be false, since they are separate objects.
BOOL sameContent = [s1 isEqual:s2]; // will be true, because they both are "Something"
The first snippet compares the values of the pointers themselves, just as if they were any primitive type like an int. If the addresses are the same, the expression will evaluate true.
The second sends the message isEqual: to one of the connection instances. Any class can override isEqual: to define "equality" with another instance. It's entirely possible for a class's implementation of isEqual: to be:
- (BOOL)isEqual: (id)obj
{
return arc4random_uniform(2) ? YES: NO;
}
So, no, for almost all classes they are not equivalent. (NSObject, which has the "default" implementation of isEqual:, uses the objects' hashes, which, again by default, are their addresses.)
It sounds like using the equality operator, ==, is correct in your case.
So i'm overriding isEquals and hash to compare custom objects to be able to remove duplicates from a NSArray. The problem is that i'm missing some values in the list which contains no duplicated items, and it seems that my hash or isEquals implementation is wrong. The custom object is a Course object which has some variables like: id and name I'll put the code here:
- (BOOL)isEqual:(id)object {
if ([object isKindOfClass:[Course self]]) {
return YES;
}
if(self == object){
return YES;
}
else {
return NO;
}
}
- (unsigned)hash {
NSString *idHash = [NSString stringWithFormat: #"%d", self._id];
return [idHash hash];
}
Then, after querying the database i put the values in an array and then in a set which should remove the duplicated items like this:
NSMutableSet *noDuplicates = [[NSMutableSet alloc] initWithArray:tempResults];
Can you see what i'm doing wrong in the isEquals or hash implementation?
Thanks a lot.
Step 1. Decide which instance variables / state are used to determine equality. It's a good idea to make sure properties exist for them (they can be private properties declared in a class extension if you like).
Step 2. Write a hash function based on those instance variables. If all the properties that count are objects, you can just xor their hashes together. You can also use C ints etc directly.
Step 3. Write isEqual: The normal pattern is probably to first test that both objects are in the class or a subclass of the method in which isEqual: is defined and then to test equality for all the properties.
So if a class Person has a name property (type NSString) and a number property (type int) which together define a unique person, hash might be:
-(NSUInteger) hash
{
return [[self name] hash] ^ [self number];
}
isEqual: might be
-(BOOL) isEqual: (id) rhs
{
BOOL ret = NO;
if ([rhs isKindOfClass: [Person class]]) // do not use [self class]
{
ret = [[self name] isEqualToString: [rhs name]] && [self number] == [rhs number];
}
return ret;
}
I don't think it is stated as an explicit requirement in the doc but it is probably assumed that equality is symmetric and transitive i.e.
[a isEqual: b] == [b isEqual: a] for all a and b
[a isEqual: b] && [b isEqual: c]implies [a isEqual: c] for all a, b, c
So you have to be careful if you override isEqual: for subclasses to make sure it works both ways round. This is also why the comment, do not use [self class] above.
Well, your isEqual: implementation really just tests if the two objects are the same class. That's not at all correct. Without knowing the details of your object, I don't know what a good implementation would look like, but it would probably follow the structure
- (BOOL)isEqual:(id)object {
if ([object isMemberOfClass:[self class]]) {
// test equality on all your important properties
// return YES if they all match
}
return NO;
}
Similarly, your hash is based on converting an int into a string and taking its hash. You could also just return the int itself as your hash.
Your code violates the principal of "objects that are equal should have equal hashes." Your hash method generates a hash from self._id and doesn't take that value into consideration when evaluating the equality of the objects.
Concepts in Objective-C Programming has a section on introspection where this topic has examples and coverage. isEqual is meant to answer the question of two objects are equivalent even if they are two distinct instances. So you want to return a BOOL indicating if the object should be considered equivalent. If you don't implement isEqual it will simply compare the pointer for equality which is not what you probably want.
- (BOOL)isEqual:(id)object {
BOOL result = NO;
if ([object isKindOfClass:[self class]]) {
result = [[self firstName] isEqualToString:[object firstName]] &&
[[self lastName] isEqualToString:[object lastName]] &&
[self age] == [object age];
}
return result;
}
From the NSObject Protocol Reference:
Returns an integer that can be used as a table address in a hash table
structure.
If two objects are equal (as determined by the isEqual: method), they
must have the same hash value. This last point is particularly
important if you define hash in a subclass and intend to put instances
of that subclass into a collection.
- (NSUInteger)hash {
NSUInteger result = 1;
NSUInteger prime = 31;
result = prime * result + [_firstName hash];
result = prime * result + [_lastName hash];
result = prime * result + _age;
return result;
}
So what defines two objects as equal is defined by the programmer and their needs. However, whatever methodology of equality is developed, equal objects should have equal hashes.
this is how you implement hash and isEqual (at-least the one which is working for me for purpose of identifying duplicates)
Hash Function
The Apple Doc says that the hash of two objects should be same for those which are considered equal( logically). hence I would implement the hash as below
-(unsigned int)hash
{
return 234;//some random constant
}
isEqual: method implemenation would be something like
-(BOOL)isEqual:(id)otherObject
{
MyClass *thisClassObj = (MyClass*)otherObject;
*// this could be replaced by any condition statement which proves logically that the two object are same even if they are two different instances*
return ([thisClassObj primaryKey] == [self primaryKey]);
}
More reference here : Techniques for implementing -hash on mutable Cocoa objects
Implementing -hash / -isEqual: / -isEqualTo...: for Objective-C collections
What is the diference between these two methods belonging to the NSSet class:
-(BOOL)containsObject:(id)anObject
-(id)member:(id)object
The answer lies in the return values. containsObject returns a YES or a NO depending on if the object you send belongs to that particular set.
member returns id, which means that it returns the actual object if that object is part of the set.
As an example, you have an NSSet, aSet, with anObject. anObject belongs to the set.
[aSet containsObject:anObject]; //returns YES
[aSet member:anObject]; //If the set contains an object equal to object (as determined by isEqual:) then that object (typically this will be object), otherwise nil.
If anObject does not exist in aSet:
[aSet containsObject:anObject]; //return NO
[aSet member:anObject]; //return nil
Do
for (id object in array) {
// do something with object
}
guarantee to return the objects in the order they are put in the array?
It's just shorthand for an enumerator. So yes for NSArrays, no for NSSets and NSDictionarys