一、在沙盒中写文件
在沙盒目录的Documents文件夹下添加一个plist文件,添加图片等方法相同
// 获取Documents文件夹目录
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
// 设定plist的路径
[rootPath stringByAppendingPathComponent:@"new.plist"];
// 然后在plist中写入内容
NSString *error;
// 序列化一个值“OK”
id plist = [NSPropertyListSerialization dataFromPropertyList:@"OK" format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
if(plist) {
NSLog(@"No error creating XML data.");
[plist writeToFile:plistPath atomically:YES];
}
else {
NSLog(@"%@",error);
[error release];
}
运行后在Documents文件夹下将看到一个new.plist文件
文件中有一个值OK,也可添加数组,字典等相关类型的内容,只需将上文中的“OK”换成一个(id)类型的值即可
二、拷贝文件到沙盒目录下
下面拷贝一个public.xml文件至document路径下,也可拷贝其他文件,只需将文件名和类型对应即可,尤其是database文件,一定要拷贝至沙盒才能使用。此文件不能是电脑中的文件,必须加入工程的Bundle中
// 获取Documents路径
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) lastObject];
// 设定要拷贝文件的路径及名称
NSString *xmlSandBoxPath = [documentsPath stringByAppendingPathComponent:@"public.xml"];
NSFileManager *fileManager = [NSFileManager defaultManager];
// 判断文件是否已经存在
BOOL isExisting = [fileManager fileExistsAtPath:xmlSandBoxPath];
if (!isExisting) {
// 本地无此文件,则将此文件拷贝到本地目录。
NSString *xmlFilePath = [[NSBundle mainBundle] pathForResource:@"public" ofType:@"xml"];
NSError *err;
// 将Bundle中的文件拷贝至沙盒目录下
[fileManager copyItemAtPath:xmlFilePath toPath:xmlSandBoxPath error:&err];
}
操作之后,Documents路径下就有这个文件了