=、isEqualおよびisEqualToString



Isequal Isequaltostring



1. 2つの変数を比較すると、結果は異なります。

NSString *string1 = @'123' NSString *string2 = @'123' / / Compare the memory address of two strings, and the address is the address pointing to the variable NSLog(@'----%zd',string1 == string2) / / Compare the contents of two strings NSLog(@'----%zd',[string1 isEqualToString:string2]) // The default compares the memory addresses of two strings, but if the two objects being compared are objects in the foundation framework, the system overrides the isEqual method to compare the content. NSLog(@'----%zd',[string1 isEqual:string2]) Person *person1 = [[Person alloc]init] person1.name = @'123' person1.age = 15 Person *person2 = [[Person alloc]init] person2.name = @'123' person2.age = 15 NSLog(@'++++%zd',[person1 isEqual:person2])

==の形式の場合、簡単に理解できますが、isEqualToStringとisEqualが異なるのはなぜですか?その理由は、Appleが下部で最適化しており、以下に示すように、isEqualToStringが基本的にisEqualメソッドをオーバーライドしているためです。



Person *person1 = [[Person alloc]init] person1.name = @'123' person1.age = 15 Person *person2 = [[Person alloc]init] person2.name = @'123' person2.age = 15 NSLog(@'++++%zd',[person1 isEqual:person2])

Personクラスをカスタマイズし、isEqualメソッドを書き直していないため、返される結果はNOです。 2つのオブジェクトのデフォルトはメモリアドレスです。
2.問題が再び発生しています。 Personの2つのオブジェクトの内容を比較して、それらが同じであるかどうかを確認したい場合、どうすればよいでしょうか。サンプルコードは次のとおりです。

#import 'XMGPerson.h' #import 'XMGCar.h' /* Once the isEqual: method is rewritten, it's best to override the hash method and follow these guidelines: 1.isEqual: return 2 objects of YES, the hash value must be the same 2. 2 objects with the same hash value, isEqual: return is not necessarily YES */ @implementation XMGPerson - (NSUInteger)hash { return self.age + self.no + self.name.hash + self.car.hash } - (BOOL)isEqual:(XMGPerson *)object { return [self isEqualToPerson:object] } - (BOOL)isEqualToPerson:(XMGPerson *)person { // If it is the exact same object, save the judgment behind if (self == person) return YES / / If the type of object is wrong, you do not need to compare if (![person isKindOfClass:self.class]) return NO // basic data type BOOL result = (self.age == person.age && self.no == person.no) if (result == NO) return result // object type if (self.name || person.name) { if (![self.name isEqual:person.name]) return NO } if (self.car || person.car) { if (![self.car isEqual:person.car]) return NO } return YES } @end