2011-02-07 47 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