override isEqual Objective-C

时间:2010-10-08 09:04:56

标签: objective-c

我的班级

@interface sample:NSObject{

   double x;

   double y;

}
@property double x;

@property double y;

-(sample *)initWithX: (double)x andY:(double) Y;


@implementation

@synthesize x,y

-(sample *) initWIthX: (double)x andY:(double)y{

    self = [super init];

    if(self) 
    {

      self.x = x;

      self.y = y; 

    }
     return self;

}

-(BOOL)isEqual:(id)other{

 if(other == self)
   return YES;
 if(!other || ![other isKindOfClass:[self class]])
   return NO;
 return [self isEqualToSample:other];  
}


-(BOOL)isEqualToSample:(sample *) other{

 if(self == other)    
   return YES;

 if (!([self x] ==[other x])) 
   return NO;

 if (!([self y] ==[other y]))   
   return NO;

   return YES;
}

return [self isEqualToSample:other];它显示警告:'sample'可能不响应'-isEqualToSample'。 return在没有强制转换的情况下从指针生成整数。

2 个答案:

答案 0 :(得分:5)

与警告无关,但在覆盖-isEqual:时,您还必须覆盖hash,以便[a isEqual: b]然后[a hash] == [b hash]

答案 1 :(得分:3)

您必须在使用之前声明isEqualToSample。否则,编译器假定选择器的签名采用/返回id

所以你可以在标题中,在私有类别中声明它,或者将实现放在isEqual:之前