I am trying to create a set of objects using NSMutableSet. The object is a Song, each tag has a name and an author.
code:
#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
Then put this object into 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];
}
}
}
But the strange thing happend,music3 is still in the NSMutableSet。But change to NSMutableArray,the music3 can delete.NSMutableArray’s removeObject call object’s isEqual method. I find the explain of the removeObject.Just a sentence:
Removes a given object from the set.
It’s not explain how it works.How to delete object like this way?NSMutableSet’s removeObject call which method?
The objective-c collection classes rely on
- (NSUInteger)hashto figure out equal objects.If your objects returns YES for
isEqual:but a differenthash, classes like NSSet will consider the objects different.See the discussion of hash:
Implement the hash method. Something like this should work: