使用示例:
使用场景
RewritePeron的isEqual方法重写
完整代码:
// RewritePerson.h
#import <Foundation/Foundation.h>
@interface RewritePerson : NSObject
@property (nonatomic, copy) NSString *personId;
@property (nonatomic, copy) NSString *name;
@end
// RewritePerson.m
#import "RewritePerson.h"
@implementation RewritePerson
#pragma mark - Override Methods
- (BOOL)isEqual:(id)object {
if (self == object) {
return YES;
}
if ([object isKindOfClass:[RewritePerson class]]) {
RewritePerson *rewritePerson = (RewritePerson *)object;
return [self isEqualToPerson:rewritePerson];
}
return NO;
}
- (BOOL)isEqualToPerson:(RewritePerson *)rewritePerson {
if (!rewritePerson) {
return NO;
}
BOOL isEqualPersonId = (!self.personId && !rewritePerson.personId) || [self.personId isEqualToString:rewritePerson.personId];
BOOL isEqualName = (!self.name && !rewritePerson.name) || [self.name isEqualToString:rewritePerson.name];
return isEqualPersonId && isEqualName;
}
- (NSUInteger)hash {
return [self.personId hash] ^ [self.name hash];
}
@end
// ViewController.m
#import "ViewController.h"
#import "RewritePerson.h"
#import "Person.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
/**********未重写isEqual方法的Person**************/
Person *person1 = [Person new];
person1.personId = @"personId1";
person1.name = @"name1";
Person *person2 = [Person new];
person2.personId = @"personId1";
person2.name = @"name1";
NSLog(@"person1isEqual person2 ? %@", [person1 isEqual:person2] ? @"是" : @"否");
//结果为: person1 isEqual person2 ? 否
/**********重写isEqual方法的RewritePerson**************/
RewritePerson *rewritePerson1 = [RewritePerson new];
rewritePerson1.personId = @"personId1";
rewritePerson1.name = @"name1";
RewritePerson *rewritePerson2 = [RewritePerson new];
rewritePerson2.personId = @"personId1";
rewritePerson2.name = @"name1";
NSLog(@"rewritePerson1 isEqual rewritePerson2 ? %@", [rewritePerson2 isEqual:rewritePerson2] ? @"是" : @"否");
//结果为: rewritePerson1 isEqual rewritePerson2 ? 是
}
@end
网友评论