繁体   English   中英

isEqual在Xcode中无法正常工作

[英]isEqual is not working properly in xcode

我的代码看起来正确,但是用于比较两个对象的isEqual无法正常工作。 我是iOS的新手。 没有太多资源可供检查。 [box2 isEqual:box1]总是给我编号,但应该给我。 我的代码中有任何错误,请向我建议正确的内容。 提前致谢。 期待最好的建议。

#import <Foundation/Foundation.h>
@interface Box:NSObject
{
    double length;   // Length of a box
    double breadth;  // Breadth of a box
    double height;   // Height of a box
}
@property(nonatomic, readwrite) double height; // Property

-(double) volume;
//-(id)initWithLength:(double)l andBreadth:(double)b;
@end

@implementation Box

@synthesize height; 

-(id)init
{
   self = [super init];
   if(self)
   {
   length = 2.0;
   breadth = 3.0;
   }

   return self;
}

-(double) volume
{
   return length*breadth*height;
}

@end
@class Box;
int main (int argc, const char * argv[])
{
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
   Box *box1 = [[Box alloc]init];    // Create box1 object of type Box
   Box *box2 = [[Box alloc]init];
   NSLog (@"hello world");
   box1.height = 5.0;
   NSLog (@"%ld",[box1 volume]);

   if([box2 isEqual:box1])
   {
   NSLog(@"%b",[box2 isEqual:box1]);
   }
   [pool drain];
   return 0;
}

您必须在对象中重写isEqual方法。

例如在您的“ @实现框”中

- (BOOL)isEqual:(id)object
{
    if ([object isKindOfClass:[Box class]]) {
        Box*box = (Box*)object;
        return self.height == box.height; // compare heights values
    }
    return [super isEqual:object];
}

isEqual:可以正常工作并且如文档所述,但效果不理想。

isEqual:是NSObject的属性。 如果两个对象指针相同,则返回YES,否则返回NO。 如果想要不同的结果,则需要为Box类重写isEqual。 请注意,isEqual:的参数可以是任何东西,而不仅仅是Box,因此需要小心。

显然,您不应该声明实例变量put属性,因此下面的代码假定了这一点。 编写代码的方式会使您对实例变量高度,属性高度和实例变量_height感到困惑,这会让您头疼。 它还假定您没有将Box子类化(例如,您可能有一个彩色的Box,它不应等于具有相同宽度,高度和宽度的Box)。

- (BOOL)isEqual:(id)other
{
    if (! [other isKindOfClass:[Box class]]) return NO;
    Box* otherBox = other;
    return _length == other.length && _breadth == other.breadth 
           && _height == other.height;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM