Pointer to a Pointer in Objective-C
I have an NSDictionary with some values. Usually, the values in the NSDictionary are static, but in some rare cases (user changes settings), the NSDictionary changes. The dictionary is used application wide and stored in the app delegate.
The problem that I have now: When the settings change, I release the old dictionary and create a new one. How do I now inform all the relevant parties? I thought of storing NSDictionary** pointers and deference them as I need, in order to get the NSDictionary* (there is never a case where the dictionary is released and not recreated).
NSMutableDictionary* dict = [NSMutableDictionary alloc] init];
...
NSDictionary** ref = &dict;
When I run the debugger I can see that dereferencing ref does get me dict initially. But af开发者_开发知识库ter some time, it seems that ref is pointing to nirvana. Wondering whether I need to manage memory or sth. for NSDictionary**? Since it's not a pointer to an object, retaining it doesn't make sense. But it does seem like a memory issue?
I'm not going to comment on the complexity of pointers, because that's really not relevant to this situation. Furthermore, I'm not really sure what it is that you want, but I think you are looking for a way to observe changes from one object in another. The nice thing is that Cocoa provides this out of the box.
So, you'll need to have this dictionary as a property to something (your application delegate). Then, use key-value-observing in whichever objects care, to watch that property for changes:
[appDelegate addObserver:self forKeyPath:@"dictPropertyName"];
Then, implement -observeValueForKeyPath:ofObject:change:context:
:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString:@"dictPropertyName"]) {
// your property has changed; respond to that here
}
}
Let me know if this is something like what you wanted.
Jonathan's answer is correct. However, since this is a global sort of thing, it might make as much or more sense to simply use a notification to let all interested parties know that the dictionary has changed.
Specifically, see NSNotificationCenter and NSNotification.
精彩评论