set a delegate class as Key in a NSMutableDictionary
I'm trying to create a NSMutableDictionary that has the Ke开发者_StackOverflow中文版ys made up of UIViewController delegates, like this:
-(void) registerAsLocationManagerDelegate:(id<RTALocationManagerDelegate>)lmDelegate forPeriodicUpdates:(NSTimeInterval)seconds
{
NSTimer* periodicTimer = [NSTimer scheduledTimerWithTimeInterval:seconds
target:self
selector:@selector(runPeriodicUpdates:)
userInfo:nil
repeats:YES];
[periodicUpdateDelegates setObject:periodicTimer forKey:lmDelegate];
}
However, my code crashes because with this error:
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[RTALocationsListViewController copyWithZone:]: unrecognized selector sent to instance 0x1a9750'
Any way around it? Am I doing something completely wrong by trying this? Should I approach this differently? Thanks for your help!
While NSDictionary copies keys, the CFDictionary functions do not. Use CFDictionary instead (or take advantage of "toll-free bridging").
NSDictionary keys can be any object as long as they conform to the NSCopying
protocol.
The error you are getting is because it copyWithZone
is part of this protocol, and it may not be implemented by your delegate object. - So it can't be a key.
Your choices are to get the string representation of your class and use that as a key - but this might not work if you have multiple delegates that are of the same class (because then the keys would not be unique). Or, implement the NSCopying
protocol in your delegate classes.
精彩评论