IOS中常用的四種數據持久化方法


  • (1)屬性列表:簡單 ,只能適用於小數據量
  • (2)對象歸檔:加密, 保存的方式是序列化,只能適用於小數據量
  • (3)SQLite:SQLite可移植性好,很容易使用,很小,高效而且可靠。
  • (4)CoraData :Core Data本質上是使用SQLite保存數據,但是它不需要編寫任何SQL語句。
1.屬性列表:容器對象——>property list
將數組保存到沙盒路徑下


2.對象歸檔:把數據進行序列化處理


3.SQLite
  • - (void)copyDBFile

    {

        NSFileManager *manager = [NSFileManager defaultManager];

        //如果文件存在,就不復制

        if ([manager fileExistsAtPath:[self databasePath]]) {

            return;

        }

        NSString *atPath = [[NSBundle mainBundlepathForResource:kDatabaseName ofType:nil];

        //複製數據庫文件到沙盒路徑下

        [manager copyItemAtPath:atPath toPath:[self databasePatherror:nil];

    }


    //取得數據庫文件所在的路徑

    - (NSString *)databasePath

    {

    //    NSLog(@"%@", [[NSBundle mainBundle] pathForResource:kDatabaseName ofType:nil]);

        

        return [NSHomeDirectory() stringByAppendingFormat:@"/Library/%@"kDatabaseName];

        

    //    return [[NSBundle mainBundle] pathForResource:kDatabaseName ofType:nil];

    }


    //增加一條數據

    - (BOOL)addUser:(User *)user

    {

        //數據庫對象

        sqlite3 *mysqlite = nil;


        //1.打開數據庫

        //filename:數據庫文件的路徑(C的字符串)

        //sqlite3:具體執行的數據庫對象

        int openResult = sqlite3_open([[self databasePathUTF8String], &mysqlite);

        //如果open函數執行成功,會返回0SQLITE_OK

        if (openResult != SQLITE_OK) {

            NSLog(@"數據庫打開失敗");

            return NO;

        }

        

        

        //2.準備SQL語句

        

        //可以把 sqlite3_stmt * 所保存的內容看成是 sql語句

        sqlite3_stmt *stmt = nil;

        //構造sql語句

        NSString *sql = [NSString stringWithFormat:@"insert into UserTable (username, password, phone, age) values (\"%@\", \"%@\", \"%@\", %ld)", user.username, user.password, user.phone, user.age];

        //sqlite3:具體執行的數據庫對象

        //zSql: sql語句

        //stmt: 語句保存的對象

        sqlite3_prepare(mysqlite, [sql UTF8String], -1, &stmt, NULL);

        

        //3.執行SQL語句

        int stepResult = sqlite3_step(stmt);

        if (stepResult == SQLITE_ERROR || stepResult == SQLITE_MISUSE) {

            NSLog(@"執行失敗");

        }

        

        //4.SQL語句完結

        sqlite3_finalize(stmt);

        

        //5.關閉數據庫

        sqlite3_close(mysqlite);

         

        

        return YES;

    }

    4.CoreData

    - (void)openDataBase

    {

        //1.加載數據模型文件 xcdatamodeld

        NSURL *url = [[NSBundle mainBundleURLForResource:@"DataModel" withExtension:@"momd"];

        //NSManagedObjectModel 用於加載數據模型文件

        NSManagedObjectModel *dataModel = [[NSManagedObjectModel allocinitWithContentsOfURL:url];

        

        //2.打開模型文件對應的數據庫文件

        //創建協調器對象,使用協調器管理數據庫文件

        NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator allocinitWithManagedObjectModel:dataModel];

        

        //指定數據庫文件在沙盒中的位置

        NSString *storePath = [NSHomeDirectory() stringByAppendingString:@"/Documents/DataStore.sqlite"];

        NSURL *storeURL = [NSURL fileURLWithPath:storePath];

        

        //打開一個數據文件 PersistentStore --> 數據庫文件

        /*

         1.如果文件不存在,創建新的數據庫文件

         2.如果文件存在,直接打開這個文件

         */

        NSError *error = nil;

        [psc addPersistentStoreWithType:NSSQLiteStoreType //生成的數據庫文件格式爲SQLite

                          configuration:nil

                                    URL:storeURL    //數據庫文件保存的路徑

                                options:nil

                                  error:&error];

        if (error) {

            NSLog(@"數據庫文件打開失敗");

        } else

        {

            NSLog(@"數據庫打開成功");

        }

        

        //3.操作數據庫

        context = [[NSManagedObjectContext allocinit];

        //指定context使用哪一個coordinator來操作數據庫文件

        context.persistentStoreCoordinator = psc;

        

        

    }



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章