通过代码创建plist文件

时间:2012-03-12 18:58:50

标签: objective-c arrays plist nsdictionary

我想创建一个这样的plist文件:

Not made with code.

在代码中,然后它将在Caches文件夹中。 我已经知道如何获取数据了。

3 个答案:

答案 0 :(得分:4)

你可以这样做:

//Create a Mutant Dictionary
NSMutableDictionary *theMutantDict = [[NSMutableDictionary alloc] init];

//Fill it with data
[theMutantDict setObject:@"John" forKey:@"Name"];
[theMutantDict setObject:@"Doe" forKey:@"Lastname"];

//Then search for cache dir 
NSString *libraryDir = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, 
                  NSUserDomainMask, YES) objectAtIndex:0];
NSString *cacheDir = [libraryDir stringByAppendingPathComponent:@"Caches"];

//Then write the file
NSString *filePath = [cacheDir stringByAppendingString:@"/TheFile.plist"];
[theMutantDict writeToFile:filePath atomically:YES];

答案 1 :(得分:3)

只需使用NSArray的writeToFile方法将数组存储在plist和arrayWithContentsOfFile中即可加载它。

[self.array writeToFile:path atomically:YES];

self.array = [[NSArray arrayWithContentsOfFile:path];

// or in case you need to add/remove objects (NSMutableArray):
self.array = [[[NSArray arrayWithContentsOfFile:path] mutableCopy] autorelease];

答案 2 :(得分:1)

如果您将数据存储在NSArray中,它就像这样简单:

// filling array with data ...

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachePath = [paths objectAtIndex:0];
NSString *plistPath = [cachePath stringByAppendingPathComponent:@"my_nsarray_data.plist"];
[klasserArray writeToFile:plistPath atomically:YES];

// other stuff ...