IOS 資料存放區

來源:互聯網
上載者:User

標籤:

1.資料歸檔
首先擷取路徑: filePath= [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"person.data"];

  接著設定要儲存的資料並儲存NSString *[email protected]"awdasf";

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

取出資料

NSString *str=[NSKeyedUnarchiver unarchiveObjectWithFile:filePath];

用Archive Storage多個多類資料
    首先準備資料
    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 *[email protected]"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 *[email protected]"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 資料存放區

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.