码迷,mamicode.com
首页 > 移动开发 > 详细

IOS 数据存储

时间:2016-05-13 03:44:07      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

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);
                }
            }];
        }  
    });
    
}




   

IOS 数据存储

标签:

原文地址:http://blog.csdn.net/qq_26790617/article/details/51335438

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!