iOS data storage is an important point of knowledge for iOS app development:
There is a lot of information on the Internet, but there is no systematic introduction to how the code hierarchy is used. This article for iOS slightly familiar with children's shoes, need to have a certain understanding of the principle of coredata. There are several ways to store the current storage:
- Nskeyedarchiver for simple data encryption
- Nsuserdefaults Applicable configuration parameters
- Write file operation, same as Nskeyedarchiver
- SQLite3 operation is more complex and is not recommended for use.
- CoreData replaces SQLite3, but follows Nsmanagedobjectcontext basic rules.
The UT code ensures the correct use of the method. Please read the following:
#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; IfSqlite3_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", @ "@" @ "Pukou"]; NSString *SQL2 = [NSString stringWithFormat: @ "INSERT into '%@ ' ('%@ ', '%@ ', '%@ ') VALUES ('%@ ', '%@ ') , '%@ '), @ "ptable", @ "name", @ "age", @ "address", @ "second name", @ "@", @ "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], @ "notEqual 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
The use of CoreData is slightly more complex, so put it in a helper class separately. The Entity model contains Name,age and address three properties. Can be created in a test project and generate an entity object.
#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:n IL]; 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 was equal to 2"); }-(Nspersistentstorecoordinator *) persistentstorecoordinator{if (_persistentstorecoordinator) return _persistent Storecoordinator; 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