2011-12-20 55 views
0

我知道这听起来像一个奇怪的问题,但我需要将我的NSUserDefaults的副本保存到数据库中(我的目标是提供数据库备份/恢复功能,使用一个文件,数据库)。如何在字符串中加载和保存plist?

所以我想我已经想出了如何加载到一个文件(虽然我还没有在Xcode中尝试过)。

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; 
[defaults registerDefaults:[NSDictionary dictionaryWithContentsOfFile: 
    [[NSBundle mainBundle] pathForResource:@"UserDefaults" ofType:@"plist"]]]; 

我已经GOOGLE了如何将NSUserDefaults保存到一个plist和一个字符串并返回,但还没有找到任何东西。

回答

0

您可以使用异步NSPropertyListSerialization API或仅使用NSDictionary上的同步便捷方法。

结帐在NSDictionary Apple Docs在将writeToFile的讨论:关于它是如何工作

而且更多信息自动方法,This article在可可的序列化一些好的信息一般。

使用下面的代码应该让你在路上。

//Get the user documents directory 
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; 
//Create a path to save the details 
NSString *backedUpUserDefaultsPath = [documentsDirectory stringByAppendingPathComponent:@"NSUserDefaultsBackup.plist"]; 
//Get the standardUserDefaults as an NSDictionary 
NSDictionary *userDefaults = [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]; 

//The easiest thing to do here is just write it to a file 
[userDefaults writeToFile:backedUpUserDefaultsPath atomically:YES]; 

//Alternatively, you could use the Asynchronous version 
NSData *userDefaultsAsData = [NSKeyedArchiver archivedDataWithRootObject:userDefaults]; 

//create a property list object 
id propertyList = [NSPropertyListSerialization propertyListFromData:userDefaultsAsData 
                mutabilityOption:NSPropertyListImmutable 
                  format:NULL 
                errorDescription:nil]; 
//Create and open a stream  
NSOutputStream *outputStream = [[NSOutputStream alloc] initToFileAtPath:backedUpUserDefaultsPath append:NO]; 
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; 
outputStream.delegate = self; //you'll want to close, and potentially dealloc your stream in the delegate callback 
[outputStream open]; 

//write that to the stream! 
[NSPropertyListSerialization writePropertyList:propertyList 
             toStream:outputStream 
             format:NSPropertyListImmutable 
             options:NSPropertyListImmutable 
             error:nil]; 

当你想往回走,你可以简单地这样做:

NSDictionary *dictionaryFromDisk = [NSDictionary dictionaryWithContentsOfFile:backedUpUserDefaultsPath];  

或者你可以使用从NSPropertyListSerialization,这类似于你保存它的方式流/ NSData的方法。

+0

怎么样一个NSString来/? – Jules 2011-12-20 13:35:04

+0

你可以写一个NSString到这样的文件中[[@“String to Save”writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil]'或者把它作为字典的一个关键字添加并保存,就像我之前提到的回答 – Jessedc 2011-12-22 01:13:45

相关问题