Only first object of NSMutableArray is stored in NSUserDefaults

半腔热情 提交于 2019-12-07 16:41:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!