简体   繁体   中英

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];
  } 
}

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.

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"]];
  }
} 

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—ie 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM