iOS基础之保存数据(持久化)

目录
       1. NSUserDefaults
       2. NSCoding 归档
       3. sqlite
       4. FMDB
       5. CoreData
       6. 读写文件
  1. NSUserDefaults
    用于存储系统自带类型,  缺点:不能存储自定义类类型。
    // 设值(必须调用synchronize)
    [[NSUserDefaults standardUserDefaults]setObject:@(10) forKey:@"age"];
    [[NSUserDefaults standardUserDefaults]synchronize];
    // 取值
    [[NSUserDefaults standardUserDefaults]objectForKey:@"age"];

其他设值方式(必须调用synchronize)
    [[NSUserDefaults standardUserDefaults]setBool:true forKey:@"sex"];
    [[NSUserDefaults standardUserDefaults]setInteger:10 forKey:@"age"];
    [[NSUserDefaults standardUserDefaults]setDouble:10.0 forKey:@"weight"];
    [[NSUserDefaults standardUserDefaults]setFloat:10.0f forKey:@"weight"];
  1. NSCoding
    用来存储自定义类类型。
1. 创建归档类(遵守NSCoding协议实现encodeWithCoder、initWithCoder)
Student.h
#import 
@interface Student : NSObject
@property (nonatomic,copy) NSString *name;
@property (nonatomic,assign) int age;
@end

Student.m
#import "Student.h"
@implementation Student
// 编码
-(void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeInteger:self.age forKey:@"age"];
}
// 解码
-(instancetype)initWithCoder:(NSCoder *)aDecoder{
    if(self){
        self.name=[aDecoder decodeObjectForKey:@"name"];
        self.age=(int)[aDecoder decodeIntegerForKey:@"age"];
    }
    return self;
}
@end

2.归档、解档
    Student *student=[Student new];
    // 路径
    NSString *path=[NSString stringWithFormat:@"%@/Documents/hello.archive",NSHomeDirectory()];
    // 归档
    [NSKeyedArchiver archiveRootObject:student toFile:path];
    // 解档
    student=[NSKeyedUnarchiver unarchiveObjectWithFile:path];
  1. sqlite
SQLite是一个由C编写的SQL嵌入式轻量级关系型数据库(线程不安全)
DBManger.h

#import 
@interface DBManger : NSObject
+(instancetype)sharedSingleton;
@end
DBManger.m

#import "DBManger.h"
#import 

@interface DBManger()
@end

@implementation DBManger


// ---------- 单例 ---------
static DBManger *_singleton;
+(instancetype)sharedSingleton{
    return [self new];
}
+(instancetype)allocWithZone:(struct _NSZone *)zone{
    @synchronized (self) {
        if(!_singleton){
            _singleton=[super allocWithZone:zone];
        }
    }
    return _singleton;
}
// 避免使用copy mutableCopy方法时再次创建
-(id)copyWithZone:(NSZone *)zone{
    return _singleton;
}
-(id)mutableCopyWithZone:(NSZone *)zone{
    return _singleton;
}


// ------------ 操作数据库 -----------
static sqlite3 *db = nil;

/*
 打开数据库
 */
-(void)openDB{
    // 有db则打开,没db则先创建再打开
    NSString *path=[NSString stringWithFormat:@"%@/Documents/test.db",NSHomeDirectory()];
    if(sqlite3_open([path UTF8String], &db)==SQLITE_OK){    // 打开db成功
        NSLog(@"数据库打开成功");
    }
}
/*
 关闭数据库
 */
-(void)closeDB{
    if (sqlite3_close(db) == SQLITE_OK) {
        NSLog(@"数据库关闭成功");
        db = nil;
    } else {
        NSLog(@"数据库关闭失败");
    }
}
/*
 创建表
 */
-(void)createTable{
    //
    [self openDB];
    NSString *sql=@"CREATE TABLE IF NOT EXISTS good(good_id INTEGER PRIMARY KEY AUTOINCREMENT,good_name CHAR(50) NOT NULL DEFAULT 'good',good_content CHAR(200),good_pic CHAR(100));";
    char *error;
    if(sqlite3_exec(db,[sql UTF8String], nil, nil, &error)==SQLITE_OK){
        NSLog(@"创建表成功");
    }else{
        NSLog(@"创建表失败 = %s",error);
    }
    [self closeDB];
}
/*
 删除表
 */
-(void)dropTable{
    //
    [self openDB];
    NSString *sql=@"DROP TABLE good;";
    char *error;
    if(sqlite3_exec(db,[sql UTF8String], nil, nil, &error)==SQLITE_OK){
        NSLog(@"创建表成功");
    }else{
        NSLog(@"创建表失败 = %s",error);
    }
    [self closeDB];
}

/*
 更新表
 */
- (void)insertData{
    [self openDB];
    sqlite3_stmt *stmt = nil;
    NSString *sqlStr = @"INSERT good(good_name,good_content) VALUES(?,?);";
    //        sqlStr="UPDATE TABLE good SET good_name=? WHERE good_id=?"
    //        sqlStr="DELETE FROM good WHERE good_name=?"
    if (sqlite3_prepare_v2(db, sqlStr.UTF8String, -1, &stmt, NULL) == SQLITE_OK) {
        // 索引从1开始,代表第几个问号
        sqlite3_bind_int(stmt, 1, 10);
        sqlite3_bind_text(stmt, 2,  sqlStr.UTF8String, -1, SQLITE_TRANSIENT);
        if (sqlite3_step(stmt) == SQLITE_DONE) {
            NSLog(@"新增成功");
        }
    } else {
        NSLog(@"新增数据不合法");
    }
    sqlite3_finalize(stmt);
    [self closeDB];
}

/*
 查询表
 */
- (void)queryData{
    [self openDB];
    sqlite3_stmt *stmt = nil;
    NSString *sqlStr = @"SELECT * FROM good";
    if (sqlite3_prepare_v2(db, sqlStr.UTF8String, -1, &stmt, NULL) == SQLITE_OK) {
        if (!(sqlite3_step(stmt) == SQLITE_DONE)) {
            // 单步获取每行(SQLITE_ROW为一行数据)
            while (sqlite3_step(stmt) == SQLITE_ROW) {
                int ID = sqlite3_column_int(stmt, 0);
                const unsigned char *name = sqlite3_column_text(stmt, 1);
                const unsigned char *content = sqlite3_column_text(stmt, 2);
                const unsigned char *pic = sqlite3_column_text(stmt, 3);
                NSLog(@"ID = %d , name = %@ , sex = %@, description = %@",ID,[NSString stringWithUTF8String:(const char *)name],[NSString stringWithUTF8String:(const char *)content],[NSString stringWithUTF8String:(const char *)pic]);
            }
        } else {
            NSLog(@"查询语句完成");
        }
    } else {
        NSLog(@"查询语句不合法");
    }
    
    //
    sqlite3_finalize(stmt);
    [self closeDB];
}

@end
  1. FMDB
  1. CoreData
  1. 读写文件

待续。。。

你可能感兴趣的:(iOS基础之保存数据(持久化))