⚠️版权声明:本文为博主原创文章,转载必须标明原文出处。
一、 每个iOS应用SDK都被限制在“沙盒”中,“沙盒”相当于一个加了仅主人可见权限的文件夹,苹果对沙盒有以下几条限制。
(1)应用程序可以在自己的沙盒里运作,但是不能访问任何其他应用程序的沙盒。
(2)应用程序间不能共享数据,沙盒里的文件不能被复制到其他应用程序文件夹中,也不能把其他应用程序文件夹中的文件复制到沙盒里。
(3)苹果禁止任何读、写沙盒以外的文件,禁止应用程序将内容写到沙盒以外的文件夹中。
(4)沙盒根目录里有三个文件夹:
Documents,一般应该把应用程序的数据文件存到这个文件夹里,用于存储用户数据或其他应该定期备份的信息。因为应用的沙盒机制,应用只能在几个目录下读写文件。苹果建议将程序中建立的或在程序中浏览到的文件数据保存在该目录下,iTunes备份和恢复的时候会包括此目录。
Library,存储程序的默认设置或其它状态信息,其下有两个文件夹:Caches存储应用程序再次启动所需的信息,存放缓存文件,iTunes不会备份此目录,此目录下文件不会在应用退出删除;Preferences包含应用程序偏好设置文件,不过不要在这里修改偏好设置。
tmp,提供一个即时创建临时文件的地方,即应用程序再次启动不需要的文件。
(5)iTunes在与iPhone同步时,备份所有的Documents和Library文件。
iPhone在重启时,会丢弃所有的tmp文件。
二、获取沙盒路径
//用NSHomeDirectory获取沙盒根目录
NSString *homeDirectory =
NSHomeDirectory();
NSLog(@"homeDirectory:%@",
homeDirectory);
//用用户名获取沙盒根目录
NSString *userName =
NSUserName();
NSString *rootPath =
NSHomeDirectoryForUser(userName);
NSLog(@"rootPath:%@",
rootPath);
//获取Document路径
NSArray *documentPaths
=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,
YES);
NSString *documentPath =
[documentPaths objectAtIndex:0];
NSLog(@"documentPath:%@",
documentPath);
//获取Library目录
NSArray *libraryPaths
=NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,
YES);
NSString *libraryPath =
[libraryPaths objectAtIndex:0];
NSLog(@"libraryPath:%@",
libraryPath);
//获取Cache目录
NSArray *cachesPaths =
NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES);
NSString *cachesPath =
[cachesPaths objectAtIndex:0];
NSLog(@"cachesPath:%@",
cachesPath);
//获取tmp目录
NSString *tmpDir =
NSTemporaryDirectory();
NSLog(@"tmpDir:%@",
tmpDir);
打开Finder,前往文件夹(Shift + Cmd + G)
输入沙盒根目录地址
(本例:/Users/tgyp/Library/Developer/CoreSimulator/Devices/5987A737-D1ED-46B3-A417-FFBC88FB2BD6/data/Containers/Data/Application/2490B94C-1358-4003-A64C-8B86D658A68D)
点击前往:
沙盒目录结构如下:
三、文件操作(NSFileManager)
(1)Plist文件操作
1、创建plist并写入
方式一、可以在工程中直接创建,把固定的内容写入,这个需要人工手动写入(工程里只可读取,不可以写入)
方式二、wirteToFile创建
//创建一个plist文件
NSString *documentPath
=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)
objectAtIndex:0];
//注意是stringByAppendingPathComponent,而不是stringByAppendingString
NSString
*plistPath = [documentPath
stringByAppendingPathComponent:@"animals.plist"];
NSLog(@"plistPath:%@", plistPath);
NSFileManager*fileManager =
[NSFileManagerdefaultManager];
if(![fileManager
fileExistsAtPath:plistPath]) {
//创建一个plist文件
[fileManager
createFileAtPath:plistPath
contents:nilattributes:[NSDictionarydictionary]];
}
//创建一个dic,写到plist文件里
NSArray *catChineseNameArr =
@[@"中国狸花猫",
@"波斯猫",
@"喜玛拉雅猫",
@"金吉拉",
@"英国短毛",
@"美国短毛(伟嚞的模特猫)",
@"异国短毛(加菲)",
@"东方短毛",
@"北美洲短毛",
@"暹逻猫",
@"加拿大无毛猫",
@"苏哥兰折耳",
@"高地折耳",
@"孟加拉豹猫",
@"俄罗斯蓝猫",
@"埃及猫", @"缅因猫",
@"巴曼猫",
@"挪威森林猫",
@"沙特尔猫",
@"克拉特猫",
@"哈瓦那猫",
@"布偶猫",
@"凡稀卷耳",
@"安哥拉猫",
@"新加坡猫"];
NSArray *catEnglishNameArr =
@[@"Chinese Li Hua", @"Persian
cat", @"Himalayan Cat",
@"chinchilla", @"british shorthair",
@"USA Shorthair", @"Garfield", @"Oriental
shorthair", @"Pixie-Bob", @"Siamese
cat", @"Canadian Hairless", @"Scottish
Fold", @"High Land Scotish Fold",
@"Bengal Cat", @"Russian blue cat",
@"Egyptian cat", @"Maine coon",
@"Birman", @"Norwegian Forest Cat",
@"Chartreux", @"Korat",
@"havana", @"Puppet cat", @"Curl
cat", @"Angola cat",
@"Singapura"];
NSMutableDictionary *catDict =
[NSMutableDictionarydictionaryWithCapacity:0];
for
(int i = 0; i <
catChineseNameArr.count; i ++) {
NSString *catChineseName =
catChineseNameArr[i];
NSString *catEnglishName =
catEnglishNameArr[i];
[catDict setObject:catEnglishName
forKey:catChineseName];
}
NSArray *dogChineseNameArr =
@[@"阿拉斯加",
@"哈士奇", @"泰迪犬",
@"比熊犬", @"蝴蝶犬",
@"拉布拉多", @"金毛",
@"萨摩耶", @"吉娃娃",
@"牧羊犬", @"黑背",
@"贵宾犬"];
NSArray *dogEnglishNameArr =
@[@"Alaskan Malamute",
@"Husky", @"Teddy Dog", @"Bichon
frise", @"papillon", @"The Labrador
Retriever", @"Golden Retriever",
@"Samoyed Dog", @"Chihuahua", @"Shepherd
Dog", @"German shepherd",
@"Poodle"];
NSMutableDictionary *dogDict =
[NSMutableDictionarydictionaryWithCapacity:0];
for
(int i = 0; i <
dogChineseNameArr.count; i ++) {
NSString *dogChineseName =
dogChineseNameArr[i];
NSString *dogEnglishName =
dogEnglishNameArr[i];
[dogDict setObject:dogEnglishName
forKey:dogChineseName];
}
//将上面的两个小字典保存到大字典里面
NSMutableDictionary *animalsDict =
[NSMutableDictionarydictionaryWithCapacity:0];
[animalsDict
setObject:catDict
forKey:@"cat"];
[animalsDict
setObject:dogDict
forKey:@"dog"];
BOOL
isSuccess = [animalsDict writeToFile:plistPath
atomically:YES];
if
(isSuccess) {
NSLog(@"创建animals.plist成功!");
} else {
NSLog(@"创建animals.plist失败!");
}
查看目录文件(成功创建)
双击打开Plist文件:
方式三、也可以将工程中plist文件复制到沙盒中
例如:用方式一创建plist,然后open as ->
Source Code
复制粘贴方式二创建的plist的源代码后Open As -> Property
List即可。
//拷贝工程中的plist文件到沙盒目录下:
NSError *error;
NSFileManager
*fileManager =
[NSFileManagerdefaultManager];
NSString *bundle =
[[NSBundlemainBundle]
pathForResource:@"animals"ofType:@"plist"];
NSString *documentPath
=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)
objectAtIndex:0];
NSString
*copyPlistPath = [documentPath
stringByAppendingPathComponent:@"animals_copy.plist"];
NSLog(@"copyPlistPath:%@",
copyPlistPath);
//如果已经存在,则删除该plist文件;否则会复制失败!(“animals.plist”
couldn’t be copied to “Documents” because an item with the same
name already exists.)
if([fileManager
fileExistsAtPath:copyPlistPath]) {
[fileManager
removeItemAtPath:copyPlistPath
error:nil
];
}
BOOL
copySuccess = [fileManager copyItemAtPath:bundle
toPath:copyPlistPath
error:&error];
if
(copySuccess) {
NSLog(@"复制到沙盒Documents成功!");
} else {
NSLog(@"复制到沙盒Documents失败!%@",error.localizedDescription);
}
2、读取Plist文件
//读取工程本地的plist文件
NSString *bundlePath =
[[NSBundlemainBundle]
pathForResource:@"animals"ofType:@"plist"];
NSMutableDictionary *localPlistDict =
[NSMutableDictionary
dictionaryWithContentsOfFile:bundlePath];
NSLog(@"localPlistDict:%@",
localPlistDict);
读取沙盒中的 plist也是一样:
NSString
*documentPath
=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)
objectAtIndex:0];
NSString
*plistPath = [documentPath
stringByAppendingPathComponent:@"animals.plist"];
NSFileManager
*manager =
[NSFileManagerdefaultManager];
if ([manager
fileExistsAtPath:plistPath]) {
NSMutableDictionary
*documentsPlistDict = [NSMutableDictionary
dictionaryWithContentsOfFile:plistPath];
NSLog(@"documentsPlistDict:%@",
documentsPlistDict);
} else {
NSLog(@"%@ do not
exists", plistPath);
}
(2)txt文件操作
NSString
*documentPath
=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)
objectAtIndex:0];
//注意是stringByAppendingPathComponent,而不是stringByAppendingString
NSString
*testDir = [documentPath
stringByAppendingPathComponent:@"test"];
NSFileManager
*manager =
[NSFileManagerdefaultManager];
NSError
*createError;
//创建文件夹(test),文件夹不会重复创建,如果相同名称的文件夹已存在,则不创建,也不会覆盖原有的文件夹!
BOOL createSuccess = [manager
createDirectoryAtPath:testDir
withIntermediateDirectories:YESattributes:nilerror:&createError];
if
(createSuccess) {
NSLog(@"创建文件夹成功:%@",
testDir);
} else {
NSLog(@"创建文件夹失败:%@",
createError.localizedDescription);
}
NSString
*testPath1 = [testDir
stringByAppendingPathComponent:@"test00.txt"];
NSString
*testPath2 = [testDir
stringByAppendingPathComponent:@"test01.txt"];
NSString
*testPath3 = [testDir
stringByAppendingPathComponent:@"test02.txt"];
NSString *string =
@"写入内容,write String";
[manager
createFileAtPath:testPath1
contents:[string
dataUsingEncoding:NSUTF8StringEncoding]
attributes:nil];
[manager
createFileAtPath:testPath2
contents:[string
dataUsingEncoding:NSUTF8StringEncoding]
attributes:nil];
[manager
createFileAtPath:testPath3
contents:[string
dataUsingEncoding:NSUTF8StringEncoding]
attributes:nil];
//获取目录列里所有文件名(包括子目录下的文件)
NSArray
*paths = [manager subpathsAtPath:documentPath];
NSLog(@"paths:%@", paths);
其他类型的文件或数据创建和读写也是相似的,在此就不累赘阐述了。
参考:
http://my.oschina.net/u/616092/blog/89339
http://blog.csdn.net/totogo2010/article/details/7669837
http://www.open-open.com/code/view/1433689785161
http://blog.csdn.net/totogo2010/article/details/7671144