containsObject not always contain, you'll use it

Conclusion: containsObject: are comparing memory address, even if the two objects are exactly the same content, different addresses, that is different. I personally think that this method should be called if there is the same object

(Do not know the beginning of knowledge, is the pit, wasted at least three hours, the same array object content, that does not include this object, MMP, their own ignorance blame it)

 

       Person contains the name and age, indicate the name and age, the array contains more than one Person, our aim is, if there is an array of the same name, and exactly the same age, a new Person to give up, how to achieve this demand? We need to override isEqual method.

Person.h

@interface Person : NSObject

@property NSString *name;

@property NSInteger age;

@end

 

Person.m 

@implementation Person

- (BOOL)isEqualToPerson:(Person *)person {

    if (!person) {

        return NO;

    }

    BOOL bIsEqualNames = [self.name isEqualToString:person.name];

    BOOL bIsEqualAges = self.age == person.age;

    return bIsEqualNames && bIsEqualAges;

}

 

#pragma mark - overloaded method isEqual

- (BOOL)isEqual:(id)object {

    if (self == object) {

        return YES;

    }

    

    if (![object isKindOfClass:[Person class]]) {

        return NO;

    }

    return [self isEqualToPerson:(Person *)object];

}

@end

 


viewController was called when: 

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view.

    

    Person *A = [[Person alloc]init];

    A.name=@"zhangsan";

    A.age=18;

    

    Person *B = [[Person alloc]init];

    B.name=@"lisi";

    B.age=15;

    

    NSMutableArray *aArray = [[NSMutableArray alloc]init];

    [aArray addObject:A];

    [aArray addObject:B];

    

    Person *C = [[Person alloc]init];

    C.name=@"zhangsan";

    C.age=18;

    

    NSLog(@"%ld",[aArray containsObject:C]);

    

}

 

最终结果,打印1,证明aArray里含有了一个姓名为zhangsan、年龄为18的人。因为Person.m里的两个方法,声明了只要姓名和年龄内容相同,就认为是同一个人。

如果注释掉Person.m里的两个方法,会打印0,因为系统默认的containsObject,比较对象的内存地址,C和A内存地址不一样,所以默认会被认为不含有C,而含有A。

Guess you like

Origin www.cnblogs.com/huangzs/p/11219235.html