iOS数据存储的几种方式

iOS的数据存储是iOS应用开发的重要知识点:

关于这方面知识,网上有很多介绍,但对于代码层次的使用方式并未有系统全面介绍。此文章针对iOS稍熟悉的童鞋,需要对CoreData的原理有一定的了解。目前存储方式大概有以下几种:

  1. NSKeyedArchiver  适用简单数据加密
  2. NSUserDefaults  适用配置参数
  3. Write  文件操作,同NSKeyedArchiver
  4. SQLite3  操作较复杂,不建议使用。
  5. CoreData  取代SQLite3,但要遵循NSManagedObjectContext基本规则。

UT代码确保使用方式正确。请阅读以下内容:

#import <XCTest/XCTest.h>
#import <sqlite3.h>
#import "CoreDataHelper.h"

@interface StudyUITests : XCTestCase

@end

@implementation StudyUITests

- (void)setUp
{
    [super setUp];
}

- (void)tearDown
{
    [super tearDown];
}

-(void)testCoreData{
    CoreDataHelper *coreHelper = [[CoreDataHelper alloc] init];
    [coreHelper coreDataTest];
}

-(void)testSqlite3{
    sqlite3 *db;

    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *databasePath = [documentPath stringByAppendingPathComponent:@"test.sqlite"];

    NSLog(@"db path: %@",databasePath);

    if(sqlite3_open([databasePath UTF8String], &db) != SQLITE_OK){
        sqlite3_close(db);
        NSLog(@"open sqlite fail!");
        NSAssert(FALSE, @"create sqlite error");
    }

    NSString *sqlCreateTable = @"CREATE TABLE IF NOT EXISTS ptable (ID INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, address TEXT)";
    char *error;
    if(sqlite3_exec(db, [sqlCreateTable UTF8String], NULL, NULL, &error) != SQLITE_OK){
        sqlite3_close(db);
        NSLog(@"can not create table.");
        NSAssert(FALSE, @"create table error");
    }

    NSString *deleteAllSql = @"delete from ptable";
    if(sqlite3_exec(db, [deleteAllSql UTF8String], NULL, NULL, &error) != SQLITE_OK){
        sqlite3_close(db);
        NSLog(@"delete values from table");
        NSAssert(FALSE, @"delete values from table");
    }

    NSString *sql1 = [NSString stringWithFormat:
                      @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES ('%@', '%@', '%@')",
                      @"ptable", @"name", @"age", @"address", @"first name", @"23", @"pukou"];

    NSString *sql2 = [NSString stringWithFormat:
                      @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES ('%@', '%@', '%@')",
                      @"ptable", @"name", @"age", @"address",@"second name", @"20", @"qixia"];

    if(sqlite3_exec(db, [sql1 UTF8String], NULL, NULL, &error) != SQLITE_OK){
        sqlite3_close(db);
        NSLog(@"can not insert sql1");
        NSAssert(FALSE, @"create insert db (sql1) error");
    }

    if(sqlite3_exec(db, [sql2 UTF8String], NULL, NULL, &error) != SQLITE_OK){
        sqlite3_close(db);
        NSLog(@"can not insert sql2");
        NSAssert(FALSE, @"create insert db (sql2) error");
    }

    //Read data and check result.

    NSString *query = @"select * from ptable";

    sqlite3_stmt *statement;

    if(sqlite3_prepare_v2(db, [query UTF8String], -1, &statement, nil) == SQLITE_OK){
        //start to traverse data

        int size = 0;
        while (sqlite3_step(statement) == SQLITE_ROW) {
            size++;
            char *name = (char*)sqlite3_column_text(statement, 1);
            int age= (int)sqlite3_column_int(statement, 2);
            char *address = (char*)sqlite3_column_text(statement, 3);

            NSString *nameStr = [[NSString alloc] initWithUTF8String:name];
            NSString *addressStr = [[NSString alloc] initWithUTF8String:address];
            NSLog(@"name: %@  age: %d address: %@",nameStr,age,addressStr);
        }
        NSAssert(size == 2, @"size should 2");
    }else{
        NSAssert(FALSE, @"query db error");
    }
    sqlite3_close(db);
}

-(void)testWriteToFile{
    NSString *st1 = @"first";
    NSString *st2 = @"second";

    NSArray *array = [NSArray arrayWithObjects:st1,st2, nil];
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSAssert(path != nil, @"path is nil");
    NSString *filename = [path stringByAppendingPathComponent:@"test.data"];
    NSAssert([array writeToFile:filename atomically:YES],@"write successfully");

    NSMutableArray *savearray = [NSMutableArray arrayWithContentsOfFile:filename];

    NSAssert([[savearray objectAtIndex:0] isEqualToString:st1], @"not equal to str1");
    NSAssert([[savearray objectAtIndex:1] isEqualToString:st2], @"not equal to str2");

}

-(void)testUserDefault{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *name = @"test";
    [defaults setObject:name forKey:@"name"];

    UIImage *image = [UIImage imageNamed:@"photo"];

    NSData *imageData = UIImagePNGRepresentation(image);
    [defaults setObject:imageData forKey:@"image"];

    //now read from data

    NSString *name1=  [defaults objectForKey:@"name"];
    NSData *imageData1 = [defaults objectForKey:@"image"];

    NSAssert([name1 isEqualToString:name], @"name1 is equal to test");
    NSAssert([imageData1 isEqualToData:imageData], @"image data is not equal");

}

-(void)testKeyedArchiver{
    NSString *save1 [email protected]"test1";
    NSString *save2 [email protected]"test2";

    NSArray *array = [NSArray arrayWithObjects:save1, save2, nil];
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

    NSString *filename = [path stringByAppendingPathComponent:@"savedatatest"];
    NSLog(@"filename : %@",filename);

    //save data
    NSAssert([NSKeyedArchiver archiveRootObject:array toFile:filename],@"archive successfully.");

    array = [NSKeyedUnarchiver unarchiveObjectWithFile:filename];

    save1 = [array objectAtIndex:0];

    NSAssert([save1 isEqualToString:@"test1"], @"save1 must equals to test1");

    save2 = [array objectAtIndex:1];
    NSAssert([save2 isEqualToString:@"test2"], @"save1 must equals to test2");

}

@end

CoreData的使用稍微复杂一些,所以将其单独放入Helper类中。Entity model包含name,age 和 address 三个属性。可在测试工程创建,并生成Entity对象。

#import "CoreDataHelper.h"
#import <CoreData/CoreData.h>
#import "Entity.h"

@interface CoreDataHelper()

@property (strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;

-(NSPersistentStoreCoordinator *)persistentStoreCoordinator;
-(NSManagedObjectContext *)managedObjectContext;
-(NSManagedObjectModel *)managedObjectModel;

@end
@implementation CoreDataHelper

-(void)coreDataTest{
    NSError *error = nil;

    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Entity" inManagedObjectContext:self.managedObjectContext];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDescription];

    NSArray *oldResult = [[self.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
    for (Entity *bb in oldResult) {
        [self.managedObjectContext deleteObject:bb];
    }
    NSAssert([self.managedObjectContext save:&error], @"deleting.....");

    /******insert *****/
    Entity *entity = [[Entity alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:nil];

    entity.name = @"test";
    entity.age = [NSNumber numberWithInt:20];
    entity.address = @"beijing";

    [self.managedObjectContext insertObject:entity];
    NSAssert([self.managedObjectContext save:&error], @"inserting.....");

    /*****query *****/
    NSSortDescriptor *sortDescription = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:NO];
    NSArray *sortDescriptions = [[NSArray alloc] initWithObjects:sortDescription, nil];
    [request setSortDescriptors:sortDescriptions];

    NSMutableArray *array = [[self.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];

    for (Entity *bb in array) {
        NSLog(@"name: %@ age:%@ address:%@",bb.name,bb.age,bb.address);
    }
    NSAssert([array count] == 1, @"count size is equal to 1");

    /***** update and check****/
    NSArray *updateResult = [[self.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
    Entity *first = [updateResult objectAtIndex:0];
    first.name = @"one";
    NSAssert([self.managedObjectContext save:&error], @"updating.....");

    updateResult = [[self.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
    first = [updateResult objectAtIndex:0];
    NSAssert([first.name isEqualToString:@"one"], @"need to equeal one");

    /**** insert and check ****/
    entity = [[Entity alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:nil];

    entity.name = @"test2";
    entity.age = [NSNumber numberWithInt:23];
    entity.address = @"nanjing";
    [self.managedObjectContext insertObject:entity];
    NSAssert([self.managedObjectContext save:&error], @"inserting.....");
    array = [[self.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
    for (Entity *bb in array) {
        NSLog(@"name: %@ age:%@ address:%@",bb.name,bb.age,bb.address);
    }
    NSAssert([array count] == 2, @"now size is equal to 2");

}

-(NSPersistentStoreCoordinator *)persistentStoreCoordinator{
    if(_persistentStoreCoordinator)
        return _persistentStoreCoordinator;

    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

    NSURL *storeURL = [NSURL fileURLWithPath:[documentPath stringByAppendingPathComponent:@"person.sqlite"]];

    NSError *error = nil;

    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

    if(![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]){
        NSLog(@"persistent error : %@",[error userInfo]);
    }
    return _persistentStoreCoordinator;
}

-(NSManagedObjectContext *)managedObjectContext{
    if(_managedObjectContext)
        return _managedObjectContext;

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];

    if(coordinator){
        _managedObjectContext = [[NSManagedObjectContext alloc] init];
        [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return  _managedObjectContext;
}

-(NSManagedObjectModel *)managedObjectModel{
    if(_managedObjectModel)
        return _managedObjectModel;

    NSURL *modeUrl = [[NSBundle mainBundle] URLForResource:@"Entity" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modeUrl];
    return  _managedObjectModel;
}

@end

iOS数据存储的几种方式,布布扣,bubuko.com

时间: 2025-01-02 17:26:34

iOS数据存储的几种方式的相关文章

Android——数据存储(四种方式之一)SharedPrefereces

Android--数据存储(四种方式) 1.SharedPrefereces   轻量级.XML  存储文件名,数据保存在data/data/basepackage/shared_prefs/myopt.xml中   实例-收藏-记住密码自动登录 //一种轻量级的数据存储方式//通过KEY 存入数据--putxxxx(key,value) 取出数据--getxxxx(key  default)   2.读写SD卡  SD的根目录  适用于数据流读写 3.SQLite  轻量级.dp文件多用于手机

Android——数据存储(四种方式之二)读写SD卡

Android--数据存储(四种方式) 1.SharedPrefereces 只能保存一些简单的数轻量级.XML  存储文件名, 数据保存在data/data/basepackage/shared_prefs/myopt.xml中    实例-收藏-记住密码自动登录 //一种轻量级的数据存储方式//通过KEY 存入数据--putxxxx(key,value) 取出数据--getxxxx(key  default) 2.读写SD卡  SD的根目录  适用于数据流读写 实现步骤:加入读写SD卡权限

Android开发之数据存储的四种方式之SharedPreferences

Android项目开发中使用的数据存储方式有:网络存储.sqlite存储.File存储和SharedPreferences存 储,四种存储方式对应的Demo别人是NetworkDemo.SqliteDemo.FileDemo和SharedPreferencesDemo, 根据应用的场景选择其中一种或多种方式,比如在登录界面验证,需要将用户名和密码通过SharedPreferences方式保存,注册信息的时候需要通 过网络将数据存储到后台数据库中.结合一个登录界面的验证,使用SharedPrefe

android 数据存储的几种方式

总体的来讲,数据存储方式有三种:一个是文件,一个是数据库,另一个则是网络.其中文件和数据库可能用的稍多一些,文件用起来较为方便,程序可以自己定义格式:数据库用起稍烦锁一些,但它有它的优点,比如在海量数据时性能优越,有查询功能,可以加密,可以加锁,可以跨应用,跨平台等等:网络,则用于比较重要的事情,比如科研,勘探,航空等实时采集到的数据需要马上通过网络传输到数据处理中心进行存储并进行处理. 对于Android平台来讲,它的存储方式也不外乎这几种,按方式总体来分,也是文件,数据库和网络.但从开发者的

Andriod中数据存储的五种方式

数据存储在开发中是使用最频繁的,在这里主要介绍Android平台中实现数据存储的5种方式,分别是: 1 使用SharedPreferences存储数据 2 文件存储数据 3 SQLite数据库存储数据 4 使用ContentProvider存储数据5 网络存储数据 下面将为大家一一详细介绍. 第一种: 使用SharedPreferences存储数据 SharedPreferences是Android平台上一个轻量级的存储类,主要是保存一些常用的配置比如窗口状态,一般在 Activity中 重载窗

六:数据存储的五种方式(一)

iOS开发中数据存在五种存储方式之三: 1.plist(XML属性列表归档) 2.偏好设置 3.NSKeydeArchiver归档(存储自定义对象) 一.plist(XML属性列表归档)只能存取对象类文件 第一种方式:(四个文件夹都可以取出路径) 1 //获取沙盒路径 2 NSString *home = NSHomeDirectory(); 3 //获取documents的路径两种方式(其它三个文件夹也能获取) 4 NSString *path = [home stringByAppendin

IOS数据持久化的4种方式

9.1 数据持久化概述 9.2 iOS应用程序目录结构 9.3 读写属性列表 9.4 对象归档 9.5 访问SQLite 9.1 数据持久化概述 iOS中可以有四种持久化数据的方式: 属性列表.对象归档.SQLite3和Core Data 9.2 iOS应用程序目录结构 iOS应用程序运行在Mac os模拟器时候,有一下临时目录模拟器3.1.3为例子: /Users/tony/Library/Application Support/iPhone Simulator/3.1.3/Applicati

ios数据存储的几种常用方式

1.NSKeyarchiver 2.NSUserDefault 3.PList 4.Write 5.SQLite 6.KeyChain 示例: 1.NSKeyarchiver 将数据存入文件: NSString *rootDir = NSHomeDirectory(); NSString *path = [rootDir stringByAppendingPathComponent:@"test.txt"]; NSMutableData *data = [NSMutable data]

【iOS开发-75】iOS数据存储的三种简单方式:plist、preference以及用NSCoding存储对象

实际开发中,存储数据主要是用SQLite.而在练习中,我们主要用如下三种存储方式. (1)利用plist存储简单地NSString.NSArray.NSDictionary等. (2)利用preference存储,和上面的类似,存储的是简单的数据,本质上还是一个plist文件. (3)利用NSCoding存储对象这些复杂的数据,本质上是一个data文件,需要被存储的类遵守NSCoding协议并实现init和encode方法. 代码如下: --在ViewController.m中 - (void)