简体   繁体   English

如何将 plist 保存到 NSUserDefaults

[英]how to save plist to NSUserDefaults

I am trying to save a .plist I have created into my NSUserDefaults so that I can save the data that I am putting into it, so if the app is stopped (removed from multitasking bar) I do not loose the values.我正在尝试将我创建的.plist保存到我的NSUserDefaults中,以便我可以保存我放入其中的数据,因此如果应用程序停止(从多任务栏中删除)我不会丢失这些值。

I have been pointed to this tutorial here在这里被指到这个教程

In it is has this sample code.其中有这个示例代码。

-(void)saveToUserDefaults:(NSString*)myString
{
    NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];

    if (standardUserDefaults) {
        [standardUserDefaults setObject:myString forKey:@"Prefs"];
        [standardUserDefaults synchronize];
    }
}

-(NSString*)retrieveFromUserDefaults
{
    NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
    NSString *val = nil;

    if (standardUserDefaults) 
        val = [standardUserDefaults objectForKey:@"Prefs"];

    return val;
}

What I would like some help with is how dose the above relate to saving .plists ?我需要帮助的是上述内容与保存.plists有何关系?

I have a .plist controller class which reads the bundle .plist creates a new .plist in the root document then reads and writes to that... how so I use the above to save it when the app exits or turns off?我有一个.plist controller class,它读取 bundle .plist在根文档中创建一个新的.plist ,然后对其进行读取和写入...如何在应用程序退出或关闭时使用上面的内容保存它?

This is how I am loading and writing to my .plist , at the moment using singlettons and it being in its own class.这就是我加载和写入我的.plist的方式,目前使用单例并且它在它自己的 class 中。

#pragma mark Singleton Methods
+ (id)sharedManager {
    @synchronized(self) {
        if (sharedMyManager == nil)
            sharedMyManager = [[self alloc] init];
    }
    return sharedMyManager;
}
- (id)init {
    if (self = [super init]) {

        // Data.plist code
        // get paths from root direcory
        NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
        // get documents path
        NSString *documentsPath = [paths objectAtIndex:0];
        // get the path to our Data/plist file
        NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"EngineProperties.plist"];

        // check to see if Data.plist exists in documents
        if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath])
        {
            // if not in documents, get property list from main bundle
            plistPath = [[NSBundle mainBundle] pathForResource:@"EngineProperties" ofType:@"plist"];
        }

        // read property list into memory as an NSData object
        NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
        NSString *errorDesc = nil;
        NSPropertyListFormat format;
        // convert static property liost into dictionary object
        NSDictionary *tempRoot = (NSMutableDictionary *)[NSPropertyListSerialization propertyListFromData:plistXML mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&errorDesc];
        if (!tempRoot)
        {
            NSLog(@"Error reading plist: %@, format: %d", errorDesc, format);
        }
        // assign values
        self.signature = [tempRoot objectForKey:@"Signature"];
        self.version = [tempRoot objectForKey:@"Version"];
        self.request = [tempRoot objectForKey:@"Request"];
        self.dataVersion = [tempRoot objectForKey:@"Data Version"];

        man = [cacheValue objectForKey:@"Man"];
        mod = [cacheValue objectForKey:@"Mod"];
        sub = [cacheValue objectForKey:@"SubMod"];

        cacheValue = [tempRoot objectForKey:@"Cache Value"];
    }


    - (void) saveData:(NSString *)methodName signature:(NSString *)pSignature Version:(NSNumber *)pVersion request:(NSNumber *)rNumber dataVersion:(NSNumber *)dvReturned cacheValue:(NSNumber *)cValue;
    {
        // get paths from root direcory
        NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
        // get documents path
        NSString *documentsPath = [paths objectAtIndex:0];
        // get the path to our Data/plist file
        NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"EngineProperties.plist"];

        // set the variables to the values in the text fields
        self.signature = pSignature;
        self.version = pVersion;
        self.request = rNumber;
        self.dataVersion = dvReturned;

        //do some if statment stuff here to put the cache in the right place or what have you.
        if (methodName == @"manufacturers")
        {
            self.man = cValue; 
        }
        else if (methodName == @"models")
        {
            self.mod = cValue;
        }
        else if (methodName == @"subMod")
        {
            self.sub = cValue;
        }

        self.cacheValue = [NSDictionary dictionaryWithObjectsAndKeys:
                           man, @"Manufacturers",
                           mod, @"Models",
                           sub, @"SubModels", nil];


        NSDictionary *plistDict = [NSDictionary dictionaryWithObjectsAndKeys:
                                   signature, @"Signature",
                                   version, @"Version",
                                   request, @"Request",
                                   dataVersion, @"Data Version",
                                   cacheValue, @"Cache Value", nil];



        NSString *error = nil;
        // create NSData from dictionary
        NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];

        // check is plistData exists
        if(plistData)
        {
            // write plistData to our Data.plist file
            [plistData writeToFile:plistPath atomically:YES];

            NSString *myString = [[NSString alloc] initWithData:plistData encoding:NSUTF8StringEncoding];
            //        NSLog(@"%@", myString);
        }
        else
        {
            NSLog(@"Error in saveData: %@", error);
            //        [error release];
        }
    }


    @end

You can't write a .plist into NSUserDefaults , at least not practically.您不能将.plist写入NSUserDefaults ,至少实际上不能。 To achieve this you'll have to write specific keys from the .plist into NSUserDefaults which is basically like saving two copies of all of your data.为此,您必须将.plist中的特定键写入NSUserDefaults ,这基本上就像保存所有数据的两个副本。 You can think of NSUserDefaults as an invisible .plist that you can read and write to, without ever being able to actually see the file.您可以将NSUserDefaults视为一个不可见的.plist ,您可以对其进行读取和写入,而无需真正看到该文件。 Using NSUserDefaults , you will be able to restore saved values even if the app has been killed in multitasking.使用NSUserDefaults ,即使应用程序在多任务处理中被杀死,您也可以恢复保存的值。

However, how you choose between .plist and NSUserDefaults should be based off of how much data you need to save.然而,你如何在.plistNSUserDefaults之间做出选择应该基于你需要保存多少数据。 Apple recommends only saving small amounts of data to NSUserDefaults . Apple 建议只将少量数据保存到NSUserDefaults If you need to save a lot of information then .plist is the way to go. Either that or of course Core-Data .如果您需要保存大量信息,那么.plist是通往 go 的途径。要么是那个,要么当然是Core-Data

.plist is a key-value pair file. .plist 是一个键值对文件。 Which is essentially a dictionary.这本质上是一本字典。 When you store data in a.plist you are persisting it.当您将数据存储在 a.plist 中时,您就是在持久化它。 You can get it back even your app is killed.即使您的应用程序被杀死,您也可以取回它。

NSUserDefaults does the same. NSUserDefaults 做同样的事情。 It is more cleaner and faster.它更干净,更快。 So either one approach is enough.因此,任何一种方法都足够了。

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

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