OC-目录操作

这篇博客深入探讨了iOS应用中的沙盒机制,包括其特点和内部文件夹结构。介绍了NSData对象用于二进制数据处理,NSFileManager对象在文件管理中的应用,以及常见的文件操作如拷贝、删除和移动。还详细讲解了字符串路径的操作,并通过实例展示了如何使用NSFileHandle。此外,博主还分享了如何使用plist文件存储数组和字典数据,以及归档与解档的概念和实践代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.沙盒

1. 什么是沙盒

沙盒:iOS应用程序只能在系统为该程序创建的文件系统中读取文件,不可以区其他地方访问,此区域被称为沙盒。一般情况下,所有非代码文件都要保存在此,例如:图像,图标,声音,影像,属性列表,文本文件等。

2. 沙盒的特点

每个应用程序都有自己独立的沙盒。
应用程序无法访问其他应用程序的沙盒。
应用程序请求的数据都要通过权限检测,假如不符合条件的话,不会放行。

3. 沙盒里面的文件夹

1. DOcuments: 苹果建议将程序中建立的或在程序中浏览到的文件数据保存在该目录下,iTunes备份和恢复的时候会包括此目录。
2. Library/Preferences: 存储程序的默认设置或者其他状态信息。
3. Library/Caches: 存放缓存文件,iTunes不会备份此目录,次目录下的文件不会在应用退出后删除。
4. tmp: 提供一个即时创建临时文件的地方。

4. Code

	//获取沙盒的路径(用户根目录)
        NSString *homeDir = NSHomeDirectory();
        NSLog(@"%@",homeDir);
        //获取临时文件路径(tmp)
        NSString *tempDir = NSTemporaryDirectory();
        NSLog(@"%@", tempDir);
        //获取Documents路径方式一
        NSString *documentsDir = [homeDir stringByAppendingString:@"/Documents"];
        NSLog(@"%@", documentsDir);
        //获取Documents路径的方式二
        NSString *documentsDir2 = [homeDir stringByAppendingPathComponent:@"Documents"];
        NSLog(@"%@",documentsDir2);
        //获取Documents路径的方式三(IOS环境一下一般只有一个元素)
        NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSLog(@"%@", array[0]);


二.NSData对象,二进制对象

1. NSData的作用

若将OC对象存放在本地文件中,需要讲OC对象转化为NSData才能存放在本地。

2. Code

		 NSString * string = @"12345";
        //NSString -> data
        NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
        
        //data->stirng
        NSString *newStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];


        NSLog(@"newStr = %@", newStr);

三. NSFileManager对象

1. NSFileManager的作用

NSFileManager可用来对文件和文件夹进行操作。

2. Code

//获取文件管理器(单例对象)
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        //创建一个目录
        NSString *filePath = @"/Users/xxxxxxx/Desktop/test";
        NSError *error;
        //判断目录是否存在
        if (![fileManager fileExistsAtPath:filePath]) {
            //参数二. 补齐缺失路径(创建多级目录)
            [fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:&error];
        }
        if (error) {
            NSLog(@"error = %@", error);
        }
        
        //文件遍历-浅遍历 --只遍历当前目录下的文件,不遍历二级目录里面的文件
        NSString *filePath1 = @"/Users/xxxxxxx/Desktop/Car";
        NSArray *array = [fileManager contentsOfDirectoryAtPath:filePath1 error:&error];
        if (error) {
            NSLog(@"error = %@", error);
        }
        NSLog(@"%@", array);
        
        //文件遍历 -深遍历 --全部遍历
        NSArray *array1 = [fileManager subpathsOfDirectoryAtPath:filePath1 error:&error];
        if (error) {
            NSLog(@"error = %@", error);
        }
        NSLog(@"%@", array1);


四. 文件的常见操作

1. 拷贝、删除、移动

2. Code

		NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *filePath = @"/Users/xxxxxx/Desktop/test";
        if (![fileManager fileExistsAtPath:filePath]) {
            [fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
        }
        
        //copy
        NSString *copyPath = @"/Users/xxxxxx/Desktop/test1";
        [fileManager copyItemAtPath:filePath toPath:copyPath error:nil];
        
        //move
        NSString *movePath = @"/Users/xxxxxx/Desktop/test1/test";
        [fileManager moveItemAtPath:filePath toPath:movePath error:nil];
        
        //remove
        [fileManager removeItemAtPath:copyPath error:nil];


五. 字符串路径的常见操作

1. 路径切割,拼接,后缀名操作

2. Code

		//获取根目录
        NSString *homeDir = NSHomeDirectory();
        NSLog(@"%@", homeDir);
        
        //路径切割
        NSArray *array = [homeDir pathComponents];
        NSLog(@"%@",array);
        
        NSString *filePath = @"/Users/xxxxxx/Desktop/Car/Person.m";
        //获取后缀名
        NSString *extensing = [filePath pathExtension];
        NSLog(@"%@", extensing);
        //删除最后的子路径
        NSString *str = [filePath stringByDeletingLastPathComponent];
        NSLog(@"%@", str);
        NSString *result = [filePath stringByDeletingPathExtension];
        NSLog(@"%@", result);


六. NSFileHandle

1. NSFileManager和NSFileHandle的区别

NSFileManager主要用于管理文件,提供了创建文件的方法
NSFileHandle主要用于操作文件内容,没有提供创建文件的方法

2. Code

		NSFileManager *fileManger = [NSFileManager defaultManager];
        
        NSString *strContent = @"hell world";
        NSData *data = [strContent dataUsingEncoding:NSUTF8StringEncoding];
        NSString *filePath = @"/Users/xxxxxx/Desktop/test/temp.txt";
        //创建文件
        if (![fileManger fileExistsAtPath:filePath]) {
            [fileManger createFileAtPath:filePath contents:data attributes:nil];
        }
        
        //三种文件操作模式
        __unused NSFileHandle *readHandle = [NSFileHandle fileHandleForReadingAtPath:filePath];
        __unused NSFileHandle *writeHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
        NSFileHandle *updateHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
        NSData *date1 = [updateHandle readDataToEndOfFile];
        NSString *string = [[NSString alloc]initWithData:date1 encoding:NSUTF8StringEncoding];
        NSLog(@"%@", string);
        
        //读取一段
        [updateHandle seekToFileOffset:0];
        NSData *data2 = [updateHandle readDataOfLength:3];
        NSLog(@"%@", [[NSString alloc]initWithData:data2 encoding:NSUTF8StringEncoding]);
        
        //追加
        [updateHandle seekToEndOfFile];
        [updateHandle writeData:data];


七. plist文件形式存储数据

    1. 用来存储数组,字典等类型的书籍

    2. Code

<span style="font-size:10px;">        //字符串快速存入本地
        NSString *str = @"helloWorled";
        NSString *filePath = @"/Users/xxxxxx/Desktop/test/temp.plist";
        [str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
        //快速把一个文件的内容转化为字符串
        NSString *str1 = [[NSString alloc]initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
        NSLog(@"%@", str1);
        
        //数组写入本地
        NSArray *array = @[@"one", @"two", @"three"];
        [array writeToFile:filePath atomically:YES];
        
        NSArray *array1 = [[NSArray alloc]initWithContentsOfFile:filePath];
        NSLog(@"%@",array1);
        
        //字典写入本地
        NSDictionary *dic = @{@"1":@"11", @"2":@"22",@"3":@"33"};
        [dic writeToFile:filePath atomically:YES];
        
        NSDictionary *dic1 = [[NSDictionary alloc]initWithContentsOfFile:filePath];
        NSLog(@"%@", dic1);
</span>


八. 归档与解档

    1. 概念

        归档:对自定义对象进行序列化操作,使其可以存储到本地
        解档:对自定义对象进行反序列化操作,转化为数据

    2. Code

Person.h
            #import <Foundation/Foundation.h>
            //NSCodeing 归档协议
            @interface Person : NSObject <NSCoding>
            @property (nonatomic, copy)NSString *name;
            @property (nonatomic, assign)NSInteger age;
            @end
        Person.m
            #import "Person.h"


            @implementation Person
            //归档方法
            - (void)encodeWithCoder:(NSCoder *)coder
            {
                [coder encodeObject:_name forKey:@"name"];
                [coder encodeInteger:_age forKey:@"age"];
            }
            //解档方法
            - (instancetype)initWithCoder:(NSCoder *)coder
            {
                self = [super init];
                if (self) {
                    _name = [coder decodeObjectForKey:@"name"];
                    _age = [coder decodeIntegerForKey:@"age"];
                }
                return self;
            }
            - (NSString *)description
            {
                return [NSString stringWithFormat:@"name=%@, age=%ld", _name, _age];
            }
            @end
        main.m
            #import <Foundation/Foundation.h>
            #import "Person.h"
            int main(int argc, const char * argv[]) {
                @autoreleasepool {
                    Person *person = [Person new];
                    person.name = @"大白";
                    person.age = 22;
                    
                    NSString *filePath = @"/Users/xxxxxx/Desktop/test/temp.plist";
                    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:person];
                    [data writeToFile:filePath atomically:YES];
                    
                    id obj = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
                    NSLog(@"%@", obj);
                }
                return 0;
            }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值