简体   繁体   English

如何更新NSUserDefault

[英]How to update an NSUserDefault

I have the following code which should update a value in NSUserDefaults: 我有以下代码,它应该更新NSUserDefaults中的值:

- (id) createBoardWithTitle:(NSString *)pTitle withScores:(NSArray *)pScores andNames:(NSArray *)pNames andDisplayStrings:(NSArray *)pStrings orderBy:(NSString *)pOrder ofType:(NSString *)pType
{

    if((self == [super init]))
    {

        boardEntries = [NSMutableArray arrayWithCapacity:10];

        // Build the data

            for(...){
               // populate boardEntries
            }


        // create an Dictionary to save
        NSDictionary *savedData = [NSDictionary dictionaryWithObjectsAndKeys:pType, @"type", pOrder, @"order", boardEntries, @"entries", nil];

            // Load the old boards
        NSDictionary *existingBoards = [[NSUserDefaults standardUserDefaults] objectForKey:@"BlockDepotLeaderboards"];

            // Create a mutable dictionary to replace the old immutable dictionary
        NSMutableDictionary *newBoards = [NSMutableDictionary dictionaryWithCapacity:[existingBoards count]+1];

            // transfer the old dictionary into the new dictionary
        [newBoards addEntriesFromDictionary:existingBoards];

            // add the new board to the new dictionary
        [newBoards setObject:savedData forKey:pTitle];

            // check to make sure it looks like it should by eye
        NSLog(@"New Boards: %@", newBoards);

            // Replace the old date in NSUserdefaults
        [[NSUserDefaults standardUserDefaults] setObject:newBoards forKey:@"BlockDepotleaderboards"];
            // Update: Do I really need to call this?
        [[NSUserDefaults standardUserDefaults] synchronize];

            // Check to make sure it looks as it should by eye
        NSLog(@" Defaults--- %@", [[NSUserDefaults standardUserDefaults] objectForKey:@"BlockDepotLeaderboards"]);
    }

    return self;

}

As far as I can tell, that's the pertinent code. 据我所知,这是相关的代码。 It's probably "wordier" than it needs to be perhaps. 它可能比它需要的更“啰嗦”。 But as I understand it, anything returned from NSUserDefaults will be immutable, so I have to recreate it as a Mutable object, add what needs adding then replace the object in NSUserDefaults. 但据我了解,从NSUserDefaults返回的任何内容都是不可变的,因此我必须将其重新创建为Mutable对象,添加需要添加的内容然后替换NSUserDefaults中的对象。 And I think what I'm trying above should work. 而且我认为我在上面尝试的应该有效。

the output for NSLog(@"New Boards: %@", newBoards) id NSLog的输出(@“New Boards:%@”,newBoards)id

New Boards: {
    "Marathon: Times" =     {
        entries =         (
                        {
                displayString = "10:00";
                name = "Tom Elders";
                score = 600;
            },
                        {
                displayString = "10:30";
                name = "A.R. Elders";
                score = 630;
            },
                        {
                displayString = "11:00";
                name = "L. Lancaster-Harm";
                score = 660;
            },

            // and so on.....

        );
        order = ASC;
        type = TIMES;
    };
    String = Test;
}

"String = test" is just a test entry and is set in the AppDelegate.m file like this: “String = test”只是一个测试条目,并在AppDelegate.m文件中设置如下:

if(![[NSUserDefaults standardUserDefaults] objectForKey:@"BlockDepotLeaderboards"]){

    NSMutableDictionary *leadboardHolder = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"Test", @"String", nil];      
    [[NSUserDefaults standardUserDefaults] setObject:leadboardHolder forKey:@"BlockDepotLeaderboards"];
    [[NSUserDefaults standardUserDefaults] synchronize];



}else{
    NSLog(@"Leaderboards Dict Exists %@", [NSUserDefaults standardUserDefaults]);
}

So I know that what I'm after is definitely there. 所以我知道我所追求的肯定是在那里。 I just know this is going to be something stupid that I'm missing. 我只是知道这将是一个让我失踪的愚蠢行为。 But I can't see it or figure it out. 但我无法看到它或弄明白。

Can anyone see what I'm messing up? 任何人都可以看到我搞砸了什么?

As far as I can tell, that's the pertinent code. 据我所知,这是相关的代码。 It's probably "wordier" than it needs to be perhaps. 它可能比它需要的更“啰嗦”。 But as I understand it, anything returned from NSUserDefaults will be immutable, so I have to recreate it as a Mutable object, add what needs adding then replace the object in NSUserDefaults. 但据我了解,从NSUserDefaults返回的任何内容都是不可变的,因此我必须将其重新创建为Mutable对象,添加需要添加的内容然后替换NSUserDefaults中的对象。

An easier way is to make a mutableCopy of the immutable dictionary like this: 一种更简单的方法是制作不可变字典的mutableCopy,如下所示:

NSMutableDictionary *newBoards = [[immutableDict mutableCopy] autorelease];
[newBoards setObject:savedData forKey:pTitle];

Also, synchronize is used to force saving the user defaults to disk. 此外, synchronize用于强制将用户默认值保存到磁盘。 It's only influencing what you see when you open the plist in the Finder. 它只会影响您在Finder中打开plist时所看到的内容。 From the perspective of the application NSUserDefaults is always up-to-date. 从应用程序的角度来看, NSUserDefaults始终是最新的。 Also, the defaults are saved automatically every little while, so the only time you likely ever need to call synchronize is when your application terminates. 此外,默认值会每隔一段时间自动保存,因此您可能需要调用synchronize的唯一时间是应用程序终止时。

According to the docs: 根据文件:

A default object must be a property list, that is, an instance of (or for collections a combination of instances of): NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. 默认对象必须是属性列表,即(或集合的实例组合)的实例:NSData,NSString,NSNumber,NSDate,NSArray或NSDictionary。

Are you sure about all the objects you are trying to serialise? 您确定要尝试序列化的所有对象吗? Take a look at NSKeyedArchiver 看看NSKeyedArchiver

Also look at this question Why NSUserDefaults failed to save NSMutableDictionary in iPhone SDK? 另请看这个问题为什么NSUserDefaults无法在iPhone SDK中保存NSMutableDictionary?

At first save anything: 首先保存任何东西:

[[NSUserDefaults standardUserDefaults] setObject:@"Previous Value" forKey:@"Name"];

Then run this code again to update value of the same key: 然后再次运行此代码以更新相同密钥的值:

[[NSUserDefaults standardUserDefaults] setObject:@"Updated Value" forKey:@"Name"];

you dont need to call [[NSUserDefaults standardUserDefaults] synchronize] due to performance issue.call it only it required. 由于性能问题,你不需要调用[[NSUserDefaults standardUserDefaults] synchronize.Call它只需要它。 iOS manages it well. iOS管理得很好。

You dont need to remove object. 你不需要删除对象。 Just update the same key. 只需更新相同的密钥即可。 It will update the Value of that particular key. 它将更新该特定键的值。 Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM