Comparing objects in Obj-C

后端 未结 4 1869
青春惊慌失措
青春惊慌失措 2020-12-03 04:01

How does one compare objects in Objective-C?

Is it as simple as == ?

I want to check an array for an object and if it doesnt exist add it to the array other

4条回答
  •  醉梦人生
    2020-12-03 04:44

    Implement isEqual: and hash

    Per the Apple documentation on NSObject you need to implement isEqual: and hash at a minimum. Below you'll find one way to implement object equality, of course how to implement hash enters the land of serious debate here on StackOverflow, but this will work. General rule - you need to define what constitutes object equality and for each unique object they should have a unique hash. It is best practice to add an object specific equality method as well, for example NSString has isEqualToString:.

    - (BOOL)isEqual:(id)object
    {
        BOOL result = NO;
    
        if ([object isKindOfClass:[self class]]) {
            CLPObject *otherObject = object;
            result = [self.name isEqualToString:[otherObject name]] &&
            [self.shortName isEqualToString:[otherObject shortName]] &&
            [self.identifier isEqualToString:[otherObject identifier]] &&
            self.boardingAllowed == [otherObject isBoardingAllowed];
        }
    
        return result;
    }
    
    - (NSUInteger)hash
    {
        NSUInteger result = 1;
        NSUInteger prime = 31;
    
        result = prime * result + [_name hash];
        result = prime * result + [_shortName hash];
        result = prime * result + [_identifier hash];
        result = prime * result + _boardingAllowed;
    
        return result;
    }
    

提交回复
热议问题