我正在尝试使用NSMutableSet创建一组对象。对象是一首歌,每个标签都有一个名字和一个作者。
代码:
#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];
}
}
}但奇怪的是,music3仍然在NSMutableSet中。但是更改为NSMutableArray,music3可以删除.NSMutableArray的removeObject call对象的isEqual方法。我发现removeObject.Just的解释是一句话:
Removes a given object from the set.NSMutableSet的removeObject调用了哪种方法?NSMutableSet的works.How调用了哪个方法?
发布于 2013-01-12 20:08:56
objective-c集合类依赖于- (NSUInteger)hash来确定相等的对象。
如果您的对象为isEqual:返回YES,但返回的是不同的hash,那么像NSSet这样的类将把这些对象视为不同的对象。
查看有关hash的讨论
如果两个对象相等(由
isEqual:方法确定),则它们必须具有相同的哈希值。如果您在一个子类中定义了hash,并打算将该子类的实例放入一个集合中,那么最后一点尤其重要。
实现散列方法。像这样的东西应该是有效的:
- (NSUInteger)hash {
return [self.author hash] ^ [self.name hash];
}https://stackoverflow.com/questions/14293135
复制相似问题