Create plist file via code

好久不见. 提交于 2019-12-13 05:39:15

问题


I want to create a plist file like this:

in code, and then it will be in the Caches folder. I already know how to fetch the data.


回答1:


You can do it like this:

//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];



回答2:


Just use the writeToFile-method of NSArray to store the array in a plist and arrayWithContentsOfFile to load it.

[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];



回答3:


If you got your data stored in an NSArray it's as easy as this:

// 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 ...


来源:https://stackoverflow.com/questions/9673140/create-plist-file-via-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!