0

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 after 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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Folks, please see @bbum's answer. His idea is to use NSNotificiationCenter instead, which will certainly simplify this for when you have lots of observers that care about changes to this object.
4

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.

1 Comment

I agree that this is a more common solution to that problem - KVC is nice in a lot of cases but for something like a whole array changing, it's probably simpler to just use a notification that anyone can listen for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.