Reputation: 819
EDIT: REAL SITUATION
MyAppDelegate has these resources:
@property (nonatomic, strong) NSDictionary *page1;
@property (nonatomic, strong) NSDictionary *page2;
@property (nonatomic, strong) NSDictionary *page3;
Here's what they look like when I init them:
self.page1 = @{@"videoPath":myPath, @"leftText":self.buttonTitle1, @"menuButtons":@[page2,page3]};
self.page2 = @{@"videoPath":myPath, @"leftText":@"long text", @"menuButtons":@[page1,page3]};
self.page3 = @{@"videoPath":myPath, @"leftText":@"another text", @"menuButtons":@[page1,page2]};
So each menuButtons key holds a reference to other objects.
Take this example: at a certain point user edits the buttonTitle1 variable, writing a new text (eg: "my new button title"). I'd like other dictionarios (page2 and page3) will reflect this modification, so inspecting page2[@"menuButtons"] will give me an NSArray of "my new button title" (page1's leftText key) and "another text" (page3's leftText key).
Consider that there are around 100 pages and users can edit buttonTitle1 several times.
How can I keep my dictionaries updated?
ORIGINAL -NOT DETAILED- QUESTION:
Given a NSDictionary with a key and a value, I'd like to keep the contents of NSDictionary updated, so when someone will edit the value OUTSIDE the NSDictionary it will reflect that modification. I don't know how to explain this in english, so please take this example:
NSNumber *number = [NSNumber numberWithInt:1];
NSDictionary *dict = @{@"test":number};
NSLog(@"%@", dict); // print "test = 1"
number = [NSNumber numberWithInt:2];
NSLog(@"%@", dict); // print "test = 1" but I'd expect "test = 2"
I know that NSDictionary takes a copy of the object, so is there any other component or workaround to accomplish this?
Please note that I've tried with NSMutableDictionary and aslo with NSMapTable with no luck.
Upvotes: 1
Views: 313
Reputation: 119031
NSDictionary
doesn't take a copy of the object, it takes a copy of the key.
What you are doing is changing a pointer unassociated with the dictionary, so the dictionary has no idea it changed. You can't really make the dictionary aware.
What you can do is to put a mutable object into the dictionary and then change its internal state. A wrapper class will do if you need to.
For instance if you put a mutable dictionary into the dictionary and then change the contents of the mutable dictionary (not a pointer to the mutable dictionary though, take care here) and log the dictionary you will see the resulting log output change.
Upvotes: 2