如何将plist保存到NSUserDefaults

时间:2012-04-11 00:57:05

标签: iphone ios plist nsuserdefaults

我正在尝试将我创建的.plist保存到我的NSUserDefaults中,以便我可以保存我放入的数据,因此如果应用已停止(从多任务栏中删除)我没有放弃这些价值观。

我已经指出了这个教程here

它有这个示例代码。

-(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的关系如何?

我有一个.plist控制器类,它读取包.plist在根文档中创建一个新的.plist然后读取和写入...我怎么这样使用上面的在应用程序时保存它 退出或关闭?

这就是我加载和写入.plist的方式,目前使用单片机并且它在自己的类中。

#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

2 个答案:

答案 0 :(得分:6)

您不能将.plist写入NSUserDefaults,至少不能写入.plist。要实现这一点,您必须将NSUserDefaults中的特定密钥写入NSUserDefaults,这基本上就像保存所有数据的两个副本一样。您可以将.plist视为您可以读取和写入的不可见NSUserDefaults,而无法实际查看该文件。使用.plist,即使应用程序在多任务处理中被杀死,您也可以恢复已保存的值。

但是,您在NSUserDefaultsNSUserDefaults之间的选择应基于您需要保存的数据量。 Apple建议仅​​将少量数据保存到.plist。如果您需要保存大量信息,那么Core-Data即可。无论是当然还是{{1}}。

答案 1 :(得分:0)

.plist是一个键值对文件。这本质上是一本字典。 将数据存储在.plist中时,您将保留它。即使您的应用程序被杀,您也可以将其恢复。

NSUserDefaults也是如此。它更清洁,更快。所以任何一种方法都足够了。