IOS 数据存储

1.数据归档
首先获取路径: filePath= [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"person.data"];

  接着设置要存储的数据并存储NSString *strValue=@"awdasf";

  BOOL isSuccess=[NSKeyedArchiver archiveRootObject:strValue toFile:filePath];

取出数据

NSString *str=[NSKeyedUnarchiver unarchiveObjectWithFile:filePath];

用归档存储多个多类数据
    首先准备数据
    CGPoint point = CGPointMake(10.0, 20.0);
    NSString *info = @"坐标点";

    NSInteger value = 100;

   设置文件路径

    manyPath = [NSHomeDirectory() stringByAppendingPathComponent:@"many.archiver"];
    NSMutableData *data = [[NSMutableData alloc]init];
    NSKeyedArchiver *archvier = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
    
    对多个数据对象进行归档
    [archvier encodeCGPoint:point forKey:@"kPoint"];
    [archvier encodeObject:info forKey:@"kInfo"];
    [archvier encodeInteger:value forKey:@"kValue"];
    [archvier finishEncoding];
    [data writeToFile:multiHomePath atomically:YES];
    解档获取数据
    NSMutableData *dataR = [[NSMutableData alloc]manyPath ];
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:dataR];
    CGPoint pointR = [unarchiver decodeCGPointForKey:@"kPoint"];
    NSString *infoR = [unarchiver decodeObjectForKey:@"kInfo"];
    NSInteger valueR = [unarchiver decodeIntegerForKey:@"kValue"];

    [unarchiver finishDecoding];

2.使用NSUserDefault存取数据
    定义NSUserDefault对象,存储数据
    NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
    NSString *strValue=@"defaults string";
    [defaults setObject:strValue forKey:@"strName"];
    取出数据
     NSString *strValue=[defaults objectForKey:@"strName"];

3.使用Sqlite数据库

首先引入框架libsqlite3.0

    定义全局变量

    sqlite3 *m_db;

    //设置数据库路径
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *strPath=[paths objectAtIndex:0];
    NSString *strFinalPath=[strPath stringByAppendingString:@"personInfo.sqlite"];
    //打开或创建数据库
    if(sqlite3_open([strFinalPath UTF8String], &m_db)!=SQLITE_OK)
    {
    
        sqlite3_close(m_db);
        NSLog(@"数据库打开失败");
    }
     创建数据表PERSONINFO
   
    NSString *strCreateTable=@"CREATE TABLE IF NOT EXISTS PERSONINFO (ID INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,age INTEGER,address TEXT)";
    [self executeSQl:strCreateTable];

插入数据

strInsertDate=[NSString stringWithFormat:@"INSERT INTO '%@' ('%@','%@','%@')VALUES('%@','%@','%@')",@"PERSONINFO",@"name",@"address",@"age",userName,userAddress,userAge];
    [self executeSQl:strInsertDate];

更新数据
 strUpdate=[NSString stringWithFormat:@"UPDATE %@ SET address='%@' WHERE %@='%@'",tableName,strAddress,valueName,strSearch];
    [self executeSQl:strUpdate];
删除数据
    strDelete=[NSString stringWithFormat:@"DELETE FROM %@ WHERE %@='%@'",tableName,valueName,strSearch];
    [self executeSQl:strDelete];

 执行除查询以外的所有SQL语句
-(void)executeSQl:(NSString*)m_sql
{
    char *error;
    if(sqlite3_exec(m_db, [m_sql UTF8String], NULL, NULL, &error)!=SQLITE_OK)
    {
        sqlite3_close(m_db);
        NSLog(@"SQL 语句执行失败");
    }
}

 查询数据库

        sqlQuery = [NSString stringWithFormat:@"SELECT * FROM %@",strDataBase];
        sqlQuery = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE %@='%@'",strDataBase,strValueName,strValue];
       sqlite3_stmt * statement;
    if (sqlite3_prepare_v2(m_db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK) {
        while (sqlite3_step(statement) == SQLITE_ROW) {

若存在,则获取数据
            char *name = (char*)sqlite3_column_text(statement, 1);
            NSString *nsNameStr = [[NSString alloc]initWithUTF8String:name];
         
            int age = sqlite3_column_int(statement, 2);
            NSString *nsAgeStr=[NSString stringWithFormat:@"%d",age];
            
            char *address = (char*)sqlite3_column_text(statement, 3);
            NSString *nsAddressStr = [[NSString alloc]initWithUTF8String:address];
}

}
    sqlite3_close(m_db);


4.使用FMDB数据库(操作比Sqlite方便,需要引入类库)
  定义全局变量
    FMDatabase *m_db;
    NSString *strFinalPath;

    设置数据库路径
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *strPath=[paths objectAtIndex:0];
    strFinalPath=[strPath stringByAppendingString:@"personInfo.sqlite"];

创建数据库
    m_db=[FMDatabase databaseWithPath:strFinalPath];


创建表
-(void)createTable
{
    if ([m_db open]) {
        NSString *sqlCreateTable =  [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS '%@' ('%@' INTEGER PRIMARY KEY AUTOINCREMENT, '%@' TEXT, '%@' INTEGER, '%@' TEXT)",@"PERSONINFO",@"ID",@"name",@"age",@"adress"];
        BOOL res = [m_db executeUpdate:sqlCreateTable];
        if (!res) {
            NSLog(@"error when creating db table");
        } else {
            NSLog(@"success to creating db table");
        }
        [m_db close];
    }
}

插入数据
-(void)insertData
{
    if ([m_db open]) {
        NSString *insertSql1= [NSString stringWithFormat:
                               @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES ('%@', '%@', '%@')",
                              @"PERSONINFO",@"name",@"age",@"adress", @"yt", @"123", @"xt"];
        BOOL res = [m_db executeUpdate:insertSql1];
        NSString *insertSql2 = [NSString stringWithFormat:
                                @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES ('%@', '%@', '%@')",
                                @"PERSONINFO",@"name",@"age",@"adress", @"yy", @"124", @"bj"];
        res = [m_db executeUpdate:insertSql2];
        
        if (!res) {
            NSLog(@"error when insert db table");
        } else {
            NSLog(@"success to insert db table");
        }
        [m_db close];
        
    }
}
更新数据

-(void)updateData
{
    if ([m_db open]) {
        NSString *updateSql = [NSString stringWithFormat:
                               @"UPDATE '%@' SET '%@' = '%@' WHERE '%@' = '%@'",
                               @"PERSONINFO",@"age",@"15",@"age",@"13"];
        BOOL res = [m_db executeUpdate:updateSql];
        if (!res) {
            NSLog(@"error when update db table");
        } else {
            NSLog(@"success to update db table");
        }
        [m_db close];
        
    }
}

删除数据
-(void)deleteData
{
    
    if ([m_db open]) {
        
        NSString *deleteSql = [NSString stringWithFormat:
                               @"delete from %@ where %@ = '%@'",
                               @"PERSONINFO",@"name", @"张三"];
        BOOL res = [m_db executeUpdate:deleteSql];
        
        if (!res) {
            NSLog(@"error when delete db table");
        } else {
            NSLog(@"success to delete db table");
        }
        [m_db close];
        
    }
}

查询数据
-(void)searchData
{
    if ([m_db open]) {
        NSString * sql = [NSString stringWithFormat:
                          @"SELECT * FROM %@",@"PERSONINFO"];
        FMResultSet * rs = [m_db executeQuery:sql];
        while ([rs next]) {
            int Id = [rs intForColumn:@"ID"];
            NSString * name = [rs stringForColumn:@"name"];
            NSString * age = [rs stringForColumn:@"age"];
            NSString * address = [rs stringForColumn:@"address"];
            NSLog(@"id = %d, name = %@, age = %@  address = %@", Id, name, age, address);
        }
        [m_db close];
    }
}

使用异步操作读取更改数据示例
-(void)asyncQueue
{


    FMDatabaseQueue * queue = [FMDatabaseQueue databaseQueueWithPath:strFinalPath];
    dispatch_queue_t q1 = dispatch_queue_create("queue1", NULL);
    dispatch_queue_t q2 = dispatch_queue_create("queue2", NULL);
    
    dispatch_async(q1, ^{
        for (int i = 0; i < 20; ++i) {
            [queue inDatabase:^(FMDatabase *db2) {
                
                NSString *insertSql1= [NSString stringWithFormat:
                                       @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES (?, ?, ?)",
                                       @"PERSONINFO", @"name", @"age", @"address"];
                
                NSString * name = [NSString stringWithFormat:@"jack %d", i];
                NSString * age = [NSString stringWithFormat:@"%d", 10+i];
                
                
                BOOL res = [db2 executeUpdate:insertSql1, name, age,@"xt"];
                if (!res) {
                    NSLog(@"error to inster data: %@", name);
                } else {
                    NSLog(@"succ to inster data: %@", name);
                }
            }];
        }
    });
    
    dispatch_async(q2, ^{
        for (int i = 0; i < 20; ++i) {
            [queue inDatabase:^(FMDatabase *db2) {
                NSString *insertSql2= [NSString stringWithFormat:
                                       @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES (?, ?, ?)",
                                       @"PERSONINFO", @"name", @"age", @"address"];
                
                NSString * name = [NSString stringWithFormat:@"lilei %d", i];
                NSString * age = [NSString stringWithFormat:@"%d", 10+i];
                
                BOOL res = [db2 executeUpdate:insertSql2, name, age,@"bj"];
                if (!res) {
                    NSLog(@"error to inster data: %@", name);
                } else {
                    NSLog(@"succ to inster data: %@", name);
                }
            }];
        }  
    });
    
}




   

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值