学习笔记(objective-c)-重写isEqual方法

来源:互联网 发布:软考程序员题型 编辑:程序博客网 时间:2024/04/28 23:11

objective-c 中判断两个变量是否相等有两种方式,一种是用==运算符,一种是用isEqual方法。

== 运算符只有当内存地址相等时才返回真,isEqual方法是值相等时就返回真。

也可以对isEqual方法进行重写,来满足实际项目的需求。

例:

#import <Foundation/Foundation.h>

@interface APPLECustomer : NSObject
@property (nonatomic,copy) NSString* name;
@property (nonatomic,copy) NSString* idNo;
-(id) initWithName:(NSString*) name idNo:(NSString*) idNo;
@end


#import "APPLECustomer.h"

@implementation APPLECustomer
@synthesize name=_name;
@synthesize idNo=_idNo;
-(id) initWithName:(NSString*) name idNo:(NSString*) idNo
{
if(self = [super init])
{
self.name = name;
self.idNo = idNo;
}
return self;
}
-(BOOL) isEqual:(id)other
{
//两个对象相等时返回YES
if(self==other)
{
return YES;
}
//当other不为空,并是APPLECustomer的实例时
else if(other!=nil && [other isMemberOfClass:APPLECustomer.class])
{
APPLECustomer* obj = (APPLECustomer*)other;
//如果idNo相等时返回YES
return [self.idNo isEqual:obj.idNo];
}
return NO;
}
@end


int main(int argc,char* argv[])
{
@autoreleasepool{
APPLECustomer* p1 = [[APPLECustomer alloc]initWithName:@"ipad1" idNo:@"1代"];
APPLECustomer* p2 = [[APPLECustomer alloc]initWithName:@"iphone" idNo:@"1代"];
APPLECustomer* p3 = [[APPLECustomer alloc]initWithName:@"iphone" idNo:@"2代"];
//返回1
NSLog(@"p1 isEqual p2 %d",[p1 isEqual:p2]);
//返回0
NSLog(@"p2 isEqual p3 %d",[p2 isEqual:p3]);
//返回1
NSLog(@"p1 isEqual p1 %d",[p1 isEqual:p1]);
}
}




0 0