2011-02-07 49 views
0

我有所谓的“网站”的自定义类:的NSMutableSet没有保留元素独特

#import "Site.h" 
#import <MapKit/MapKit.h> 

@implementation Site 

@synthesize name, desc, coordinate; 

+ (Site*) siteWithName:(NSString *)newName 
     andDescription:(NSString *)newDesc 
      andLatitude:(double)newLat 
      andLongitude:(double)newLon 
{ 
    Site* tmpSite = [[Site alloc] initWithName:newName 
           andDescription:newDesc 
            andLatitude:newLat 
            andLongitude:newLon]; 
    [tmpSite autorelease]; 
    return tmpSite; 
} 

- (Site*) initWithName:(NSString *)newName 
     andDescription:(NSString *)newDesc 
      andLatitude:(double)newLat 
      andLongitude:(double)newLon 
{ 
    self = [super init]; 
    if(self){ 
     self.name = newName; 
     self.desc = newDesc; 
     coordinate.latitude = newLat; 
     coordinate.longitude = newLon; 
     return self; 
    } 
    return nil; 
} 

- (NSString*) title 
{ 
    return self.name; 
} 

- (NSString*) subtitle 
{ 
    return self.desc; 
} 

- (BOOL)isEqual:(id)other { 
    if (other == self) 
     return YES; 
    if (![super isEqual:other]) 
     return NO; 
    return [[self name] isEqualToString:[other name]]; // class-specific 
} 

- (NSUInteger)hash{ 
    return [name hash]; 
} 

- (void) dealloc 
{ 
    [name release]; 
    [desc release]; 
    [super dealloc]; 
} 

@end 

我有一个名为的NSMutableSet其中allSites我通过unionSet方法添加其他组的网站来。这可以工作,并且这些网站集都会添加到allSites集中。但重复的网站不会被删除。我怀疑这与我在网站的isEqual或hashcode实现中出现的错误有关,我知道NSMutableSet用它来确保唯一性。

任何有识之士将不胜感激。

+0

设置断点的isEqual中,看看它实际上是所谓的 – Felix 2011-02-07 15:29:43

回答

1

更改isEqual方法:

- (BOOL)isEqual:(id)other { 
    if (other == self) 
     return YES; 
    if ([[self name] isEqualToString:[other name]]) 
     return YES; 
    return [super isEqual:other]; 
} 
0

你是什么Site类的超?对超类'isEqual:方法的调用看起来有点可疑,特别是如果你的类是NSObject的直接后代。在这种情况下,[super isEquals: other]基本上归结为self == other,这显然不是你想要的。这是讨论,例如,在coding guidelines for cocoa

默认情况下,isEqual:方法判断对象地址指针相等,而hash则返回一个基于对象地址产生的hash值,因此,这个不变成立。

这只是一种猜测,但...

0

的超类是NSObject的。我从以下苹果的isEqual推荐实施:

http://developer.apple.com/library/ios/#documentation/General/Conceptual/DevPedia-CocoaCore/ObjectComparison.html

我是不是太熟悉的isEqual NSObject的实现。

@ phix23。是的,这工作。 @Dirk,感谢您的解释。谢谢你们,你们在调试器中省了很多时间。

+0

不,你只能这样做,如果你超是你自己的一个类(而不是'NSObject`)。看到我编辑的答案。 – Dirk 2011-02-07 16:02:35