I have a simple messaging app, and I'm keeping a dictionary of BOOL:user
in the NSUserDefaults which simply represents if something "new" has happened in that conversation. {YES:12343}
for example, means there is a new message with user 123432, otherwise NO
.
When users interact with each other, I update that dictionary and my view accordingly. And when I leave the app, save the dictionary to the NSUserDefaults
. When I come back, I simply load it. Everything works smoothly, expect one thing.
When I tap on a conversation to open it, I set that boolean to NO
(because I assume the user has read the message) and save that modified dictionary into the NSUserDefaults
again.
Debug shows the dictionary is up to date when saved, but when I tap the "back" button, the view reloads the dictionary from the NSUserDefaults
and that dictionary is NOT up to date. So my view is showing the conversation as unread, obviously.
Now the tricky parts comes into play. If I do it again, (sometimes once, sometimes twice), the dictionary will eventually show the conversation as read (because the dictionary will finally be up to date).
This tells me some things :
- The dictionary is readable and everything is set "as it should/when it should"
- What I get from the NSUserDefaults isn't updated quick enough/at the right time.
What I fail to understand is : when should I save that dictionary and how? I'm loading it in viewWillAppear
, and saving it in didSelect
. Isn't that the right thing to do ?
Some code :
My didSelect
:
pushDict is an NSMutableDictionary
object and is never nil at that point
if (pushDict != nil){
[pushDict setObject:[NSNumber numberWithBool:NO] forKey:_friendship.objectId];
[[NSUserDefaults standardUserDefaults]setObject:pushDict forKey:@"pushDict"];
}
And the dictionary loading :
if([[NSUserDefaults standardUserDefaults]dictionaryForKey:@"pushDict"]){
pushDict = [[NSMutableDictionary alloc]initWithDictionary:[[NSUserDefaults standardUserDefaults]dictionaryForKey:@"pushDict"]];
}else{
pushDictFeel = [NSMutableDictionary alloc]init];
}