Andrew Johnson
Andrew Johnson

Reputation: 13286

Objective C: How do I make an NSMutableSet of NSMutableDictionaries, and have them be unique based on one of the dictionary values?

The reason I'm asking this is because right now I use an NSMutableSet of integers and a corresponding NSMutableArray to store the rest of the data, but I think I'm not using the language right. Here's my code:

In the init function:

self.markerList = [[NSMutableArray alloc] init];
self.markerIdSet = [[NSMutableSet alloc] init];

And the function that updates the set and array:

- (void) addMarker: (RMMarker*)marker AtLatLong:(CLLocationCoordinate2D)point {
  if (![self.markerIdSet member: [node objectForKey:@"id"]]) {
    [self.markerIdSet addObject:[node objectForKey:@"id"]];
    [self.markerList addObject:marker];
  } 
}

Upvotes: 0

Views: 4294

Answers (3)

mmmmmm
mmmmmm

Reputation: 32681

I would be a bit wary of having a mutable object as part of a key in a set as if the object changes its hash code etc could change but the set would not know about it ( unless you make the addMarker remve the object and then add it back with the new hash code)

However in your example can't you just use a dictionary (or am I missing something?)

self.markerDict = [[NSMutableDictionary alloc]init];

- (void) addMarker: (RMMarker*)marker AtLatLong:(CLLocationCoordinate2D)point {
  if ([nil != [self.markerDict [node objectForKey:@"id"]]) {
      [self.markerDict setValue:marker forKey:[node objectForKey:@"id"]];
  }
} 

Upvotes: 3

John Calsbeek
John Calsbeek

Reputation: 36497

Don't make an NSMutableSet of NSMutableDictionary directly; make a custom class that has an NSMutableDictionary property. This custom class should implement -isEqual: and -hash in terms of your id—i.e. this object will be equal to another object if the ids are equal, and two objects with the same id will have the same hash.

More documentation with regard to -isEqual: and -hash.

Upvotes: 2

Aviad Ben Dov
Aviad Ben Dov

Reputation: 6409

The NSMutableSet contains unique elements. Uniqueness is determined by the hash and isEquals methods, so in order to do what you want, you should either subclass or delegate an NSMutableDictionary and in your own concrete class implement these methods so that the specific key you require is the equality and hash factor.

Upvotes: 3

Related Questions