如何将plist保存到NSUserDefaults [英] how to save plist to NSUserDefaults

查看:77
本文介绍了如何将plist保存到NSUserDefaults的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将创建的.plist保存到我的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.

我已经在此处

其中包含此示例代码.

-(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;
}

我想帮忙的是上述剂量与节省.plists有何关系?

What I would like some help with is how dose the above relate to saving .plists?

我有一个.plist控制器类,该类读取捆绑软件.plist在根文档中创建一个新的.plist,然后对其进行读写...如何在应用程序中使用上面的方法保存它 退出还是关闭?

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的方式.

This is how I am loading and writing to my .plist, at the moment using singlettons and it being in its own 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

推荐答案

至少不能将.plist写入NSUserDefaults中.为此,您必须将.plist中的特定键写入NSUserDefaults中,这基本上就像保存所有数据的两个副本一样.您可以将NSUserDefaults视为可以读取和写入的不可见.plist,而实际上却无法看到该文件.使用NSUserDefaults,即使该应用已在多任务处理中被杀死,您仍将能够还原保存的值.

You can't write a .plist into NSUserDefaults, at least not practically. 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. 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. Using NSUserDefaults, you will be able to restore saved values even if the app has been killed in multitasking.

但是,在.plistNSUserDefaults之间进行选择的方式应基于需要保存多少数据. Apple建议仅​​将少量数据保存到NSUserDefaults.如果您需要保存大量信息,则可以使用.plist.要么当然是Core-Data.

However, how you choose between .plist and NSUserDefaults should be based off of how much data you need to save. Apple recommends only saving small amounts of data to 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保存到NSUserDefaults的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆