ユーザーデータを含む情報辞書があります。現在、アプリと同じディレクトリにあるxmlファイルに書き込まれています。ただし、cocoaを使用すると、このxmlファイルをアプリケーションバンドルまたはアプリ内のリソースディレクトリに書き込むことができると確信しています。
誰かが私にこれを行う方法を教えてもらえますか?
ユーザーデータを含む情報辞書があります。現在、アプリと同じディレクトリにあるxmlファイルに書き込まれています。ただし、cocoaを使用すると、このxmlファイルをアプリケーションバンドルまたはアプリ内のリソースディレクトリに書き込むことができると確信しています。
誰かが私にこれを行う方法を教えてもらえますか?
xmlファイルの(バンドルと比較して)でNSFileManager
toを使用することをお勧めします。
このようなもの:createFileAtPath:contents:attributes:
NSDocumentDirectory
/Documents
NSData
NSString *myFileName = @"SOMEFILE.xml";
NSFileManager *fileManager = [NSFileManager defaultManager];
// This will give the absolute path of the Documents directory for your App
NSString *docsDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
// This will join the Documents directory path and the file name to make a single absolute path (exactly like os.path.join, if you python)
NSString *xmlWritePath = [docsDirPath stringByAppendingPathComponent:myFileName];
// Replace this next line with something to turn your XML into an NSData
NSData *xmlData = [[NSData alloc] initWithContentsOfURL:@"http://someurl.com/mydoc.xml"];
// Write the file at xmlWritePath and put xmlData in the file.
BOOL created = [fileManager createFileAtPath:xmlWritePath contents:xmlData attributes:nil];
if (created) {
NSLog(@"File created successfully!");
} else {
NSLog(@"File creation FAILED!");
}
// Only necessary if you are NOT using ARC and you alloc'd the NSData above:
[xmlData release], xmlData = nil;
いくつかの参考文献:
NSFileManager
参照ドキュメント
NSData
参照ドキュメント
編集
あなたのコメントに応えて、これはNSUserDefaults
アプリの実行間でシリアル化可能なデータを保存するための典型的な使用法です:
// Some data that you would want to replace with your own XML / Dict / Array / etc
NSMutableDictionary *nodeDict1 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"object1", @"key1", nil];
NSMutableDictionary *nodeDict2 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"object2", @"key2", nil];
NSArray *nodes = [NSArray arrayWithObjects:nodeDict1, nodeDict2, nil];
// Save the object in standardUserDefaults
[[NSUserDefaults standardUserDefaults] setObject:nodes forKey:@"XMLNODELIST"];
[[NSUserDefaults standardUserDefaults] synchronize];
保存された値を取得するには(次回アプリを起動したとき、またはアプリの別の部分からなど):
NSArray *xmlNodeList = [[NSUserDefaults standardUserDefaults] arrayForKey:@"XMLNODELIST"];