存储相关

沙盒

Document:存放重要的数据,iTunes同步时会备份该目录
Library/Caches:一般存放体积大,不重要的数据,iTunes同步时不会被分该目录
Library/Preferences:存放用户的偏好设置,iTunes同步时时会备份该目录
tmp:用户存放临时文件,在程序未运行时可能会删除该文件夹中的数据,iTunes同步时不会备份该目录

沙盒路径

Document:
OC:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentFilePath = paths.firstObject;

Swift:

let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentFilePath = paths.first

1.NSUserDefaults

适合存储轻量级的本地数据,支持的数据类型有:NSNumber,NSString,NSData,NSArray,NSDictionary,BOOL,NSDate
沙盒路径为 Library/Preferences
文件格式为 .plist

优点:
·不需要关心文件名
·快速进行键值对存储
·直接存储基本数据类型

缺点:
·不能存储自定义数据
·取出的数据都是不可变的

存:
OC:

NSArray *testArray = @[@"test1", @"test2", @"test3"];
    [[NSUserDefaults standardUserDefaults] setObject:testArray forKey:@"arrayKey"];
    [[NSUserDefaults standardUserDefaults] synchronize];

Swift:

let testArray = ["test1", "test2", "test3"]
        UserDefaults.standard.set(testArray, forKey: "arrayKey")
        UserDefaults.standard.synchronize()

取:
OC:

NSArray *testArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"arrayKey"];

Swift:

let testArray = UserDefaults.standard.value(forKey: "arrayKey")

2.plist储存

plist支持的数据类型:
NSArray,NSMutableArray,NSDictionary,NSMutableDictionary,NSData,NSMutableData,NSString,NSMutableString,NSMutableString,NSNumber,NSDate,
不支持BOOL,最外层要用NSArray或NSDictionary


OC:

NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    NSString *filePath = [cachePath stringByAppendingPathComponent:@"test.plist"];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:@"jim" forKey:@"name"];
    [dict setObject:@"18" forKey:@"age"];
    [dict writeToFile:filePath atomically:YES];

Swift:

let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first
        let filePath = cachePath! + "test.plist"
        
        let dict = ["name": "jim", "age": "18"] as NSDictionary
        dict.write(toFile: filePath, atomically: true)


OC:

NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    NSString *filePath = [cachePath stringByAppendingPathComponent:@"test.plist"];
NSDictionary *t = [NSDictionary dictionaryWithContentsOfFile:filePath];

Swift:

let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first
        let filePath = cachePath! + "test.plist"
        let t = NSDictionary.init(contentsOfFile: filePath)

3.归档

·归档解档最大的好处在于可以存储自定义对象数据
·归档接档要注意iOS版本
OC:

@interface Person : NSObject
@property(nonatomic, strong) NSString *name;
@property(nonatomic, strong) NSString *age;
@end
@implementation Person

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super init];
    if (self) {
        _name = [coder decodeObjectForKey:@"name"];
        _age = [coder decodeObjectForKey:@"age"];
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeObject:self.age forKey:@"age"];
}

+ (BOOL)supportsSecureCoding {
    return YES;
}

@end

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentFilePath = paths.firstObject;
    NSString *filePath = [documentFilePath stringByAppendingPathComponent:@"test.archive"];
    
    Person *p1 = [[Person alloc] init];
    p1.name = @"jim";
    p1.age = @"18";
    
    if (@available(iOS 11.0, *)) {
        NSError *error = nil;
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:p1 requiringSecureCoding:YES error:&error];
        [data writeToFile:filePath atomically:YES];
    } else {
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:p1];
        [data writeToFile:filePath atomically:YES];
    }

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentFilePath = paths.firstObject;
    NSString *filePath = [documentFilePath stringByAppendingPathComponent:@"test.archive"];
    NSData *data = [[NSData alloc] initWithContentsOfFile:filePath];
    if (@available(iOS 11.0, *)) {
        NSError *error = nil;
        Person *person = [NSKeyedUnarchiver unarchivedObjectOfClass:Person.class fromData:data error:&error];
        NSLog(@"%@", person);
    } else {
        Person *person = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        NSLog(@"%@", person);
    }

Swift

class Person: NSObject,NSSecureCoding {
    var name: String!
    var age: String!
    
    override init() {
        super.init()
    }
    required init?(coder aDecoder: NSCoder) {
        name = aDecoder.decodeObject(forKey: "name") as? String
        age = aDecoder.decodeObject(forKey: "age") as? String
    }
    
    func encode(with aCoder: NSCoder) {
        aCoder.encode(name, forKey: "name")
        aCoder.encode(age, forKey: "age")
    }
    static var supportsSecureCoding: Bool {
        return true
    }

}

let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
        let documentFilePath = paths.first
        let filePath = documentFilePath! + "test.archive"
        
        let p1 = Person()
        p1.name = "jim"
        p1.age = "18"
        
        if #available(iOS 11.0, *) {
            let data = try! NSKeyedArchiver.archivedData(withRootObject: p1, requiringSecureCoding: true) as NSData
            data.write(toFile: filePath, atomically: true)
        } else {
            let data = NSKeyedArchiver.archiveRootObject(p1, toFile: filePath)
        }

let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
        let documentFilePath = paths.first
        let filePath = documentFilePath! + "test.archive"
let data = NSData.init(contentsOfFile: filePath)
        if #available(iOS 11.0, *) {
            let person = try! NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data! as Data)
            print("\(person)")
        } else {
            let person = NSKeyedUnarchiver.unarchiveObject(with: data as! Data)
            print("\(person)")
        }

4.SQLite3

splite是一个轻量级,跨平台的小型数据库,可移植性比较高,有着和MySpl几乎相同的数据库语句,以及无需服务器即可使用的优点
优点:
·该方案可以存储大量的数据,存储和检索的速度非常快。
·能对数据进行大量的聚合,这样比起使用对象来讲操作要快。

缺点:
·它没有提供数据库的创建方式
·它的底层是基于C语言框架设计的, 没有面向对象的API, 用起来非常麻烦
·复杂的数据模型的数据建表,非常麻烦
在实际开发中我们都是使用的是FMDB第三方开源的数据库,该数据库是基于splite封装的面向对象的框架.OC使用 Swift使用

5.CoreData

coreData是苹果官方在iOS5之后推出的综合性数据库,其使用了对象关系映射技术,将对象转换成数据,将数据存储在本地的数据库中
coreData为了提高效率,需要将数据存储在不同的数据库中,比如:在使用的时候,最好是将本地的数据保存到内存中,这样的目的是访问速度比较快.

优点:
·可视化,且具有undo/redo能力
·可以实现多种文件格式
·苹果官方API支持,与iOS结合更紧密
缺点:
·使用麻烦
具体OC使用 Swift使用

6.Realm

Realm是由美国YCombinator孵化的创业团队历时几年打造,第一个专门针对移动平台设计的数据库
优点:
·开源
·简单易用
·跨平台
·线程安全
·便于数据库迁移

缺点:
·需要导入

OC中 pod 'Realm'
Swift中 pod 'RealmSwift'

具体OC使用 Swift使用

7.UIDocuments

使用
UIDocument 是苹果提供给我们方便的管理文档的类。在这篇文章中,会从头开始教你如何使用 UIDocument 去创建,读取,修改,更新 iOS 的文件系统。

你可能感兴趣的:(存储相关)