【IOS学习基础】文件相关

 


一、沙盒(SandBox) 

  1.沙盒机制

  1> 每个应用都有属于自己的存储空间,即沙盒。
  2> 应用只能访问自己的沙盒,不可访问其他区域。
  3> 如果应用需要进行文件操作,则必须将文件存放在沙盒中,尤其是数据库文件,在电脑上操作时,可以去访问,但是如果要装在真机上可以使用,必须将数据库文件拷贝至沙盒中。

  2.沙盒目录结构

  1> Documents:在应用中建立的文件,如数据库等可以放在这里,iTunes备份和恢复的时候会包括此目录。
  2> tmp:存放及时传送的临时文件,iTunes不会备份和恢复此目录,此目录下文件可能会在应用退出后删除。
  3> Library/Caches:存放缓存文件,iTunes不会备份此目录,此目录下文件不会在应用退出删除。
  4> Library/Preferences:应用程序偏好设置,我们经常使用的NSUserDefault就保存在该目录下的一个Plist文件中,iTnues还会同步此文件。

  3.关于几个参数

NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory directory, NSSearchPathDomainMask domainMask, BOOL expandTilde);

directory
NSSearchPathDirectory类型的enum值,表明我们要搜索的目录名称(
NSDocumentDirectory、NSCachesDirectory。

domainMask
NSSearchPathDomainMask类型的enum值,指定搜索范围,这里的NSUserDomainMask表示搜索的范围限制于当前应用的沙盒目录。还可以写成NSLocalDomainMask(表示/Library)、NSNetworkDomainMask(表示/Network)等。

expandTilde
BOOL值,表示是否展开波浪线~。我们知道在iOS中~的全写形式是/User/userName,该值为YES即表示写成全写形式,为NO就表示直接写成“~”。

  4.沙盒路径的获取

#pragma mark 沙盒主路径
-(NSString *)homePath
{
return NSHomeDirectory(); } #pragma mark 用户应用数据路径 +(NSString *)getDocuments
{ NSArray
*paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); NSString *path = [paths objectAtIndex:0]; return path; } #pragma mark 缓存数据路径 +(NSString *)getCache { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); return paths[0]; } #pragma mark 临时文件路径 +(NSString *)getTemp { return NSTemporaryDirectory(); } #pragma mark Library路径 +(NSString *)getLibrary { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES); NSString *path = [paths objectAtIndex:0]; return
path; }

开发中经常会打印沙盒的路径,除了用NSLog输出之外,还可以这样(注意,要打断点调试)

 


二、NSBundle

  1.NSBundle *mainBundle[NSBundle mainBundle];

  bundle是一个目录,其中包含了程序会使用到的资源. 这些资源包含了如图像,声音,编译好的代码,nib文件(用户也会把bundle称为plug-in). 对应bundle,cocoa提供了类NSBundle.我们的程序是一个bundle. 在Finder中,一个应用程序看上去和其他文件没有什么区别. 但是实际上它是一个包含了nib文件,编译代码,以及其他资源的目录. 我们把这个目录叫做程序的main bundle。

NSLog(@"获取app包路径:%@",mainBundle.bundlePath);

NSLog(@"获取app资源目录路径:%@",mainBundle.resourcePath);

NSLog(@"应用标识bundle Identifier:%@",mainBundle.bundleIdentifier);

NSLog(@"info.plist信息及其他:%@",mainBundle.infoDictionary);

提示:关于打印字典或数组中文乱码的问题,请自行搜索NSDitionary/NSArray + Log分类或重写他们的
-(NSString *)descriptionWithLocale:(id)locale方法。

   2.Bundle的使用

1> 新建Bundle:既然Bundle就是一个目录,那不妨新建一个文件夹,在其中放入我们需要的资源素材,然后对文件夹进行重名“文件名.bundle”,之后会弹出提示框(如下图),点击“添加”。


2> 读取自己的Bundle资源(以百度SDK为例)
百度地图的IphoneMapSdkDemo示例程序中有一个名为”mapapi.bundle"的图片资源包


而在其demo的“AnnotationDemoViewController.m"文件中,定义了这么几个宏
// 资源包文件名
#define MYBUNDLE_NAME @ "mapapi.bundle"
// 拼接mapapi.bundle资源包路径
#define MYBUNDLE_PATH [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: MYBUNDLE_NAME]  
// 获取mapapi.bundle资源包
#define MYBUNDLE [NSBundle bundleWithPath: MYBUNDLE_PATH]
// 加载资源包中规定某个文件
[[NSBundle mainBundle] pathForResource:@"XXX.png(想要获取的文件名)" ofType:nil inDirectory:@"mapapi.bundle"];
// 加载xib文件
NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"MyView" owner:nil options:nil];

 


三、NSFileManager文件管理类

  1.NSFileManager主要用于对目录、文件的基本操作,且其是一个单例对象(单例模式:一种设计模式,即一个类永远只有一个类对象),使用时NSFileManager *fm = [NSFileManager defaultManager]

  2.宏定义快速实现单例(前几天在网上看到的,觉得挺好的,记录一下)

  1> 新建一个”Singleton.h"文件,在里面粘贴如下代码

// .h
#define singleton_interface(class) + (instancetype)shared##class;

// .m
#define singleton_implementation(class) \
static class *_instance; \
\
+ (id)allocWithZone:(struct _NSZone *)zone \
{ \
    static dispatch_once_t onceToken; \
    dispatch_once(&onceToken, ^{ \
        _instance = [super allocWithZone:zone]; \
    }); \
\
    return _instance; \
} \
\
+ (instancetype)shared##class \
{ \
    if (_instance == nil) { \
        _instance = [[class alloc] init]; \
    } \
\
    return _instance; \
}

  2> 新建一个类,分别在.h文件和.m文件里面写上如下图代码,

 

  3> 使用:SingerTest *test = [SingerTest sharedSingerTest];

 

  3.方法搜集

常用路径工具函数

NSString *NSUserName(void);

返回当前登录的用户名

NSString *NSFullUserName(void);

返回当前用户的完整用户名

NSString *NSHomeDirectory(void);

返回当前主目录的路径(常用)

NSString * __nullable NSHomeDirectoryForUser(NSString * __nullable userName);

返回指定用户名的主目录

NSString *NSTemporaryDirectory(void);

返回用于创建临时文件夹的目录路径

NSString *NSOpenStepRootDirectory(void);

返回当前用户的系统根目录

 

 

 

 

 

 

文件/目录相关

- (BOOL)fileExistsAtPath:(NSString *)path;

 判断path下是否存在文件/文件夹

- (BOOL)fileExistsAtPath:(NSString *)path isDirectory:(nullable BOOL *)isDirectory;

 判断path下是否是文件
 - (BOOL)createDirectoryAtPath:(NSString *)path withIntermediateDirectories:(BOOL)createIntermediates attributes:(nullable NSDictionary<NSString *, id> *)attributes error:(NSError **)error

 新建文件夹

 参数:

1-文件夹路径。

2-YES为如果文件不存在,则创建;NO,文件夹不创建。

3-文件夹的属性,可读可写,一般传nil。

4-错误信息 。

 - (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error  移除文件/文件夹
 - (BOOL)copyItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error  复制文件/文件夹
 - (BOOL)moveItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error  移动文件/文件夹

- (BOOL)createFileAtPath:(NSString *)path contents:(nullable NSData *)data attributes:(nullable NSDictionary<NSString *, id> *)att

 新建文件

 参数:

1-文件路径(最后面拼接文件名)

2-需要新建的文件数据

3-属性

 

- (BOOL)contentsEqualAtPath:(NSString *)path1 andPath:(NSString *)path2;

 比较两个path下的文件是否相同

 

 

 

 

 

 

 

 

 

 

 

 

 

 

NSPathutilities常用路径处理方法(扩展)

- (nullable NSArray<NSString *> *)contentsOfDirectoryAtPath:(NSString *)path error:(NSError **)error NS_AVAILABLE(10_5, 2_0);

遍历path目录下的文件,并返回一个数组

- (nullable NSData *)contentsAtPath:(NSString *)path;

获取path下的文件数据

- (nullable NSArray<NSString *> *)subpathsAtPath:(NSString *)path;

以递归方式获取子项目录列表

+ (NSString *)pathWithComponents:(NSArray<NSString *> *)components;

通过一个数组创建路径

pathComponents

获取路径的组成部分,是一个数组

lastPathComponent

路径的最后一部分

pathExtension

文件扩展名

- (NSString *)stringBy+<Appending/Deleting>+Path+<Component/Extension>:(NSString *)str;

 <拼接/删除>+<路径/后缀>名在末尾

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


四、NSFileHandle文件句柄类(相当于c语言的文件File)

  1.用于针对文件的I/0操作,相当于一个文件操作手柄,能更有效的控制文件,类似C语言的文件管理。

  2.使用NSFileHandle

  1> 需要打开一个文件,然后获取一个NSFileHandle对象(注意:如果这个文件不存在,则使用下列方法时不能获取到NSFileHandle对象

// 打开一个文件并准备读取
NSFileHandle *fp = [NSFileHandle fileHandleForReadingAtPath:path];

// 打开一个文件并准备写入
NSFileHandle *fp = [NSFileHandle fileHandleForWritingAtPath:path];

// 打开一个文件并准备更新(读写)
NSFileHandle *fp = [NSFileHandle fileHandleForUpdatingAtPath:path];

  2> 对打开的文件进行I/0操作

// 写入文件
[data WriteToFile:path atomically:YES]

  3> 关闭文件(注意:在C语言中,所有操作完成之后都会关闭文件,这里也一定要关闭,为了保证文件的安全

// 关闭文件
[fp closeFile];

  3.NSFileHandle的重要概念:句柄(下面流程有助于了解句柄的作用)----具体会在后续写NSURLConnection中用到。

  给文件做一个标记,让用户下次写入文件的时候从这个标记处开始存储。而seekToEndOfFile方法则是每次存储完后都将句柄移动至该文件末尾。

 


五、NSProcessInfo(了解)

-(NSArray*)arguments  //以数组的形式返回当前进程的参数

-(int)processIdentifier  //返回进程标识符(进程id),用于识别每个正在运行的进程

-(NSString*)processName  //返回当前正在执行的进程名称

-(NSString *)globallyUniqueString  //每次调用这个方法时,都返回不同的单值字符串,可以用这个字符串生成单值临时文件名

-(NSString *)hostname  //返回主机系统的名称

-(NSUInteger)operatingSystem  //返回表示操作系统的数字
-(NSString *)operatingSystemName  //返回操作系统的名称 -(NSString *)operatingSystemVersionString  //返回操作系统的当前版本
-(void)setProcessName:(NSString *)name  //将当前进程名称设置为name。应该谨慎地使用这个方法,应为关于进程名称存在一些假设(比如用户默认的设置)

 

 

    

posted @ 2016-01-19 18:49  不忘、初心  阅读(1123)  评论(0编辑  收藏  举报