问题
I am trying to store a queue of UILocalNotification to solve the limit problem. I used this approach and it does archive and unarchive my object but only the first one.
How do I archive all objects from my NSMutableArray?
Code
// init/unarchive queue
if (self.queue == nil)
{
// try loading stored array
NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
NSData *dataRepresentingSavedArray = [currentDefaults objectForKey:@"LocalNotificationQueue"];
if (dataRepresentingSavedArray != nil) {
NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingSavedArray];
if (oldSavedArray != nil) {
self.queue = [[NSMutableArray alloc] initWithArray:oldSavedArray];
}
else
{
self.queue = [[NSMutableArray alloc] init];
}
}
else
{
self.queue = [[NSMutableArray alloc] init];
}
}
// add
[self.queue addObject:notif];
// store queue
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:self.queue] forKey:@"LocalNotificationQueue"];
If I add items 1,2,3. Restart and load. I have only 3.
Add 1,2,3. Restart and load. I have 3, 1, 2.
If it matters. This is a Phonegap/Cordova CDVPlugin.
回答1:
After
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:self.queue] forKey:@"LocalNotificationQueue"];
You need to call
[[NSUserDefaults standardUserDefaults] synchronize]
To save the user defaults.
回答2:
Try this, without the NSKeyedArchiver
:
[[NSUserDefaults standardUserDefaults] setObject: self.queue] forKey:@"LocalNotificationQueue"];
来源:https://stackoverflow.com/questions/14731111/only-first-object-of-nsmutablearray-is-stored-in-nsuserdefaults