IOS中常用的四種資料持久化方法,ios四種資料

來源:互聯網
上載者:User

IOS中常用的四種資料持久化方法,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 mainBundle] pathForResource:kDatabaseName ofType:nil];

        //複製資料庫檔案到沙箱路徑下

        [manager copyItemAtPath:atPath toPath:[self databasePath] error: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 databasePath] UTF8String], &mysqlite);

        //如果open函數執行成功,會返回0,SQLITE_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 mainBundle] URLForResource:@"DataModel" withExtension:@"momd"];

        //NSManagedObjectModel 用於載入資料模型檔案

        NSManagedObjectModel *dataModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:url];

        

        //2.開啟模型檔案對應的資料庫檔案

        //建立協調器對象,使用協調器管理資料庫檔案

        NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: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 alloc] init];

        //指定context使用哪一個coordinator來操作資料庫檔案

        context.persistentStoreCoordinator = psc;

        

        

    }



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.