ios - NSMutableSet removeObject 无法移除对象

标签 ios objective-c

我正在尝试使用 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调用对象的isEqual方法。我找到了removeObject的解释,就一句话:

Removes a given object from the set.

没有解释它是如何工作的。如何像这样删除对象?NSMutableSet的removeObject调用了哪个方法?

最佳答案

objective-c 集合类依赖 - (NSUInteger)hash找出相等的对象。

如果您的对象对 isEqual: 返回 YES但是不同的 hash,像 NSSet 这样的类会认为对象是不同的。

参见 hash 的讨论:

If two objects are equal (as determined by the isEqual: method), they must have the same hash value. This last point is particularly important if you define hash in a subclass and intend to put instances of that subclass into a collection.

实现散列方法。这样的事情应该有效:

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

关于ios - NSMutableSet removeObject 无法移除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14293135/

相关文章:

objective-c - 由于awakeFromNib时间太长而导致应用崩溃

ios - 这个 iOS 应用程序使用分段控制吗?

objective-c - 在 objective-c 中调用方法

ios - UIGestureRecognizer 拖动 UIView

ios - 如何在文本到语音合成过程中停止语音?

ios - 图片查看动画

ios - 如何在 IOS 中将表值存储到核心数据实体中

objective-c - 向所有用户发送推送通知

ios - 将来自服务器的 UTC 日期存储在 NSDate 对象中

iphone - 从互联网下载plist(数据库)?