2013-01-12 47 views
2

我想使用NSMutableSet创建一组对象。该对象是一首歌曲,每个标签都有一个名称和一个作者。NSMutableSet removeObject无法删除对象

代码:

#import "Song.h" 

@implementation Song 

@synthesize name,author; 

-(Song *)initWithName:(NSString *)n andAuth:(NSString *)a { 
    self = [super init]; 

    if (self) { 
     name = n; 
     author = a; 
    } 

    return self; 
} 

-(void)print { 
    NSLog(@"song:%@; author:%@;", name,author); 
} 

-(BOOL)isEqual:(id)obj { 
    //NSLog(@"..isEqual"); 

    if([[obj name] isEqualToString:name] 
     && [[obj author] isEqualToString:author]) { 
     return YES; 
    } 

    return NO; 
} 

-(BOOL)isEqualTo:(id)obj { 
    NSLog(@"..isEqualTo"); 

    if([[obj name] isEqualToString:name] 
     && [[obj author] isEqualToString:author]) { 
     return YES; 
    } 

    return NO; 
} 

@end 

然后把这个对象到的NSMutableSet:

int main(int argv, char *argc[]) { 
    @autoreleasepool { 
     Song *song1 = [[Song alloc] initWithName:@"music1" andAuth:@"a1"]; 
     Song *song2 = [[Song alloc] initWithName:@"music2" andAuth:@"a2"]; 
     Song *song3 = [[Song alloc] initWithName:@"music3" andAuth:@"a3"]; 

     Song *needToRemove = [[Song alloc] initWithName:@"music3" andAuth:@"a3"]; 

     NSMutableSet *ns = [NSMutableSet setWithObjects:song1, song2, song3, nil]; 

     [ns removeObject:needToRemove]; 

     for (Song *so in ns) { 
      [so print]; 
     } 
    } 
} 

但奇怪的happend,music3仍处于NSMutableSet.But变化的NSMutableArray,该music3可以删除。 NSMutableArray的removeObject调用对象的isEqual方法。我觉得removeObject.Just句子的解释:

Removes a given object from the set. 

这不是解释它是如何works.How删除对象像这样的NSMutableSet的的removeObject调用哪个方法?

回答

8

Objective-c集合类依靠- (NSUInteger)hash来计算出相同的对象。

如果您的对象为isEqual:返回YES,但不是hash,类似NSSet的类将认为对象不同。

hash讨论:

如果两个对象是相等的(如由isEqual:法测定),它们必须具有相同的散列值。如果您在子类中定义散列并打算将该子类的实例放入集合中,则最后一点尤其重要。

执行哈希方法。像这样的东西应该工作:

- (NSUInteger)hash { 
    return [self.author hash]^[self.name hash]; 
} 
+0

非常感谢! – user1971788