If the application value requires a small amount of data to be saved for program parameters and options, you can save it using Nsuserdefaults;
If the application is just a small amount of data to be saved, then use the attribute list file;
If your application has a large amount of data to store and access, you need to use the database. The iOS system has a SQLite database built into it, and the SQLite database is a truly lightweight database with no background process and the entire database corresponds to a file, This makes it easy to migrate between different devices. iOS provides two sets of APIs for accessing the SQLite database: Libsqlite3.dylib based on C language style and object-oriented core Data.
First, application sandbox
In order to provide a better security mechanism, iOS provides an application sandbox mechanism that ensures that each application can access only the data in the sandbox, avoiding conflicts with other applications. View the application sandbox in the OS X system in two ways: (1), open Finder applications, through the "commend +shift+g shortcut opens the Go to Folder dialog box, where users can enter "/user/< username >/library/" To enter the list of OS X libraries. Then enter the application of the directory in turn support/ IPhone simulator/7.0/applications subdirectory (here is the iOS simulator);
Note: Comparison of Xcode 5 and Xcode 6 simulator paths
①, Xcode 5 simulator path is:/users/username/library/application support/iphone Simulator
②, Xcode 6 simulator path is:/users/user name/Library/developer/coresimulator
The Devices folder under the 16 files corresponding to the XCODE6 under the 16 simulator, can be based on the Device.plist files under each folder to get specific which simulator:
Note: Comparison of sandbox paths for Xcode 5 and Xcode 6
The path to the ①, Xcode 5 sandbox is:/users/username/library/application support/iphone simulator/7.1-64/applications/corresponding application Folder
Document
The path to the ②, Xcode 6 sandbox is:/users/username/library/developer/coresimulator/devices/emulator udid/data/containers/bundle/applications /corresponding Application Folder
Note: Preferences for Xcode 5 and Xcode 6 compare
The path to the preferences directory in ①, Xcode 5 is:/users/username/library/application support/iphone simulator/7.1-64/applications/corresponding application Folder/ Library/preferences
The path to the preferences directory in ②, Xcode 6 is: The specific path to the Plist file created using the Nsuserdefault method is:/users/username/library/developer/coresimulator/devices/ Simulator Udid/data/library/preferences
(2), in the OS X System Command Line window, enter "defaults write Com.apple.finder appleshowallfiles-bool true", and then exit the Finder and restart the Finder to see hidden files and folders. This allows you to find the path directly.
Showing: Defaults write Com.apple.finder appleshowallfiles-bool true
Hiding: Defaults write Com.apple.finder Appleshowallfiles-bool false
Open any application folder, you can see the following file structure: ①, Documents: In addition to based on the Nsuserdefaults preference settings, the application data, files are stored in the directory; ②, Library: Nsuserdefaults based on the preferences of the parameters stored in the Library/preferences directory; ③, tmp: This directory is for application storage temporary file, when iOS performs synchronization, itunes does not back up files in the TMP directory. Therefore, when an application does not need a temporary file, it is responsible for deleting the temporary files in the TMP directory and avoiding the use of system space.
1. Obtain Documents Catalogue
nsarray* paths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);
nsstring* documentsdirectory = [Paths objectatindex:0];
/users/osx2014/library/developer/coresimulator/devices/c99acfa5-7162-497a-ba7f-0ff93c7f6867/data/containers/ Data/application/fbfaf7c5-3053-45aa-a1a4-72b98e858a24/documents
Since the Nssearchpathfordirectoriesindomains () function is not designed specifically for iOS, it was originally designed for OS X systems, Therefore, many options that use this function will not return any values. The first parameter of the function represents a lookup of the Documents folder, and the Nsuserdomainmask parameter represents only the home directory of the current user
2. Get tmp directory
nsstring* Tmppath = Nstemporarydirectory ();
/users/osx2014/library/developer/coresimulator/devices/c99acfa5-7162-497a-ba7f-0ff93c7f6867/data/containers/ data/application/fbfaf7c5-3053-45aa-a1a4-72b98e858a24/tmp/
3. Get caches catalogue
Nsarray *cachepaths = Nssearchpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask, YES);
NSString *cachesdir = [Cachepaths objectatindex:0];
/users/osx2014/library/developer/coresimulator/devices/c99acfa5-7162-497a-ba7f-0ff93c7f6867/data/containers/ Data/application/bb4c3035-9a66-4dda-a74b-0b7fc10cc901/library/caches
4. Get home directory
nsstring* homepaht = Nshomedirectory ();
/users/osx2014/library/developer/coresimulator/devices/c99acfa5-7162-497a-ba7f-0ff93c7f6867/data/containers/ data/application/bb4c3035-9a66-4dda-a74b-0b7fc10cc901
5. Thinking about the strategy of document Preservation
When an application needs to save running state and user data, it is usually selected to be saved in the Documents folder of the application sandbox, except that the data based on Nsuserdefaults will be stored in the Library/prefereences directory (Xcode 5), Temporary files for some applications are chosen to be saved in the TMP directory-once the file is out of effect, the application should immediately delete the temporary file and release the valuable storage space on the phone.
The advantages and disadvantages of using multiple files to save data are as follows: (1), Advantages: The application needs to use which part of the data to load which file, so as to avoid the one-time load of all persisted data caused by memory tension. Which part of the data the application modifies, just save the corresponding file, This prevents all persisted data from being saved at the same time. (2), disadvantage: Multi-file preservation data inevitably brings about the complexity of programming, may need to establish additional data structure to manage the persistence of content and storage of the corresponding relationship between the files.
second, application parameters and user default settings
The application holds a small amount of data (strings, scalar types, etc.), such as the application's various configuration information (such as open sound, whether the use of vibration effect, etc.), game player information (username, password, etc.), and so on, iOS provides settings bundle to manage.
1. Use Settings Bundle
The biggest advantage of setting application parameters with the settings bundle is that the application settings interface is provided entirely by the setting application, and the developer simply provides the settings bundle the set of files. Developers provide settings for applications After bundle, the application's parameter setting interface is provided by the system settings application, and the user-Set program parameters are saved by the settings, and the settings are responsible for reading the parameters of the user settings each time the settings are opened .... The application's parameter setting interface, data storage, and reading logic are all handled by the system settings application.
Add a settings Bundle to the project as follows:, click the Xcode main Menu "file"-> "New"-> "File ..." menu item; , select "Settings Bundle" under the "IOS"-> "Resource" category, and then click the "Next" button, the system enters the Save dialog box, saves the settings Bundle in the project's root directory, and the file name is " Settings.bundle ".
Open the Settings.bundle contained root.plist file in Xcode and you can see the following:
There are two child nodes under the iphone Settings schema node: (1), preference Items: The type of the node is array. This node is used to define the settings interface for this setting bundle. The node contains ITEM0, Item1, ITEM2, Item3 these 4 nodes. (2), Strings Filename: The node is of type string, and the value is root. The function of the node is to tell the system to find the Root.strings file in the *.lproj file as an internationalized resource file- Readers can find root.strings files in the En.lproj file, and if the program needs to be bundle internationalized, you can add folders such as Zh-hans.lproj and add root.strings files to these internationalized resource files.
Note: The essence of the Plist property file is Nsdictionary or Nsarray, except that the Nsdictionary key for the Plist property file can only be nsstring type, and value can be Boolean, NSData, NSDate, NSNumber, NSString, Nsarray, nsdictionary type.
Right-click to select the Show Raw keys/values menu item, which will display more authentic, unprocessed keys and value, as shown in the following figure:
Item0, Item1, ITEM2, Item3 a set entry in each corresponding settings application, each setting entry is used to set an application parameter, and each item can typically specify the following 4 generic items: (1), title: The display title of the application parameter of the configuration;
(2), type: The item configures the type of the application parameter. Type supports several property values as follows. ①, Pstextfieldspecifier: This type specifies that the application parameter is a text box that can be entered by the user in the value of the parameter; ②, Pstitlevaluespecifier: This type specifies that the application parameters are the same as the display headings; ③, Pstoggleswitchspecifier: This type specifies that the application parameter behaves as a Uiswitch control, through which the user can set the parameter to Yes or no; ④, Pssliderspecifier: This type specifies that the application parameter behaves as a UISlider control, through which the user can set a floating-point value; ⑤, Psmultivaluespecifier: This type specifies that the application parameter is represented as a list of user choices, through which the user can select one of the values; ⑥, Psgroupspecifier: This type defines a grouping; ⑦, Pschildpanespecifier: This type defines a child settings view. When a user clicks this type of setup item, the system opens a new setup interface – when defining this type of item, you must reassign a plist file to define the interface of the child settings view.
(3), key: This item is used to specify that the key-of the system that holds the application parameters will use Nsdictionary to save the application parameters, and each application parameter should be assigned a key in Nsdctionary. The value set for this key will be the key for the application parameter. (4), DefaultValue: This entry specifies the default value for the application parameter.
(1), set up grouping
The following figure:
(2), set the text box parameters
Set type to "Pstextfieldspecifier" to represent text box parameters-this program parameter allows the user to enter parameter values freely. The text box parameter can also specify the caption of the argument, key, default, and the value that holds the parameter. , the text section parameter can also specify the following options: ①, Autocapitalizationtype: Specifies the automatic capitalization type for the text box. This option supports values that are identical to the values supported by the Uitextview capitalization property. ②, AutoCorrection type: Used to specify the type of AutoCorrect for the text box. This option supports values that are identical to the values supported by the correction property of Uitextview. ③, Issecure: This property value is set to "yes", indicating that this is a password input box. ④, Keyboardtype: Specifies the type of virtual keyboard that this text box is associated with.
(3), set Uiswitch parameters
Set the type to "Psswitchspecifier" to represent an argument that supports only yes or no-this program parameter allows the user to set the parameter value through the Uiswitch control. Uiswitch parameters can also be passed by key, Title, Default specifies the key of the parameter's save parameter, the display caption, and the defaults.
(4), set UISlider parameters
Set the type to "Pssliderspecifier" to represent parameters that support only floating-point values-this program parameter allows the user to set the parameter value through the UISlider control. The UISlider parameter can also specify key to save parameters by key, default, The default value. In addition, UISlider also supports the following settings: ①, Minimum value: Specifies the minimum value represented by the slider at the leftmost edge of the uislider; ②, Maximum value: Specifies the maximum value represented by the slider at the far right of the uislider; ③, Minimum valueimage: Specifies the picture that represents the minimum value at the leftmost edge of the uislider; ④, Maximum valueimage: Specifies the picture at the far right of the uislider representing the maximum value;
Note: You need to put the picture in the settings bundle to be accessed by the settings bundle. You cannot drag directly into the settings bundle, you need to display the package content, and you can copy the picture in.
(5), set multivalued parameters
Set type "Psmultivaluespecifier" To configure a multivalued list parameter that users can select from a list of parameter values. Multivalued parameters can also specify the display title of the parameter, key, default value of the parameter by title, key and default. In addition , multivalued parameters also support the following settings: ①, titles: Array collection needs to be provided, and the collection element defines the title of multiple list items; ②, values: Need to provide an array set, the collection element defines the values of multiple list items;
(6), set the child settings view
Set the ITEM5 type to "Psgroupspecifier" and Item6 type to "Pschildpanespecifier" To configure the child settings view, which can be displayed by the title setting. You can also set the plist file name of the view by using the file Settings child.
Note: This sub-Setup view requires a my.plist file, exactly the same as the root.plist format, and you need to create a my.plist file and then display the package content and copy it to the settings bundle.
2. Use Nsuserdefaults to read and save application parameters
Get Nsuserdefaults Single Example:
nsuserdefaults* defaults = [Nsuserdefaults standarduserdefaults];
After you get the Nsuserdefault object, you can get and set the parameters by: (1), Xxxforkey: (NSString *) key: Gets the parameter value of the object according to the specified key. With different parameter value types, XXX can be changed; (2), Setxxx:value forkey: (NSString *) key: Set parameters;
When the parameter is set, the Synchronize method of Nsuserdefault object can be called to save.
For example:
nsuserdefaults* defaults = [Nsuserdefaults standarduserdefaults];
[Defaults setobject:@ "Hello, goddess" forkey:@ "key"];
[Defaults synchronize];
nsstring* name = [Defaults objectforkey:@ "key"];
Note: Here you can read and set the values in the settings bundle above
nsuserdefaults* defaults = [Nsuserdefaults standarduserdefaults];
NSLog (@ "%@", [Defaults objectforkey:@ "name"]);
NSLog (@ "%d", [Defaults boolforkey:@ "MusicOn"]);
NSLog (@ "%f", [Defaults floatforkey:@ "Gamespeed"]);
NSLog (@ "%@", [Defaults objectforkey:@ "race"]);
Third, attribute list
(1) call-(BOOL) WriteToFile: (NSString *) path atomically (bool) only if the Nsarray, Nsdictionary collection holds objects of the following types: Useauxiliaryfile method Execution Save.
①, Nsarray and Nsmutablearray; ②, Nsdictionary and nsmutabledictionary; ③, NSData and Nsmutabledata; ④, NSString and nsmutablestring; ⑤, Nsvalue and NSNumber; (2), when the data is restored, simply call Nsarray, nsdictionary xxxwithcontentsoffile: (NSString *) FilePath; method Execution Initialization
Fourth. object Archiving and native I/O APIs
If your program needs to save a custom instance, you can have the class implement the Nscoding protocol and implement the-(ID) Initwithcoder: (nscoder) Adecoder defined in the Protocol; -(void) Encodewithcoder: (Nscoder) Acoder two methods, which can then be archived using nskeyedarchive, which can be recovered using nskeyedunarchive when the program needs to reply to the object.
Fifth. Use of the SQLite database
(1), the terminal under the database
①, create folder: MkDir SQLite;
②, creating table: Create TABLE (if not exists) Table name (field name 1, field name 2 ...);
③, display table:. Table;
④, delete table: drop table table name;
⑤, insert statement: INSERT INTO table name (field name 1, field name 2 ...) values (value 1, value 2 ...)
⑥, display the contents of the table: select *from table name;
⑦, deleting table data: Delete from table name-delete all data
Delete from table name where condition-Deletes a piece of data
⑧, modify: Update table name set field name 1= value 1, field name 2= value 2 ... where condition;
⑨, query: Select field name from table name;
Select field name from table name limit n; query n data
Query sort: Select field name from table name order BY field name (DESC);
Query multiple: SELECT COUNT (*) from table name, table name data item number;
Select SUM (UID) from table name, UID and
Select AVG (UID) from table name;
⑩, exit:. Quit;
Main: The primary key CREATE TABLE Wugong (WID integer primary key auto increment name,uid);
(2), SQLite programming of iOS
Using the SQLite programming API for iOS in your project requires that you complete the following two steps:
①, for the project positive price libsqlite3.dylib
②, import libsqlite3.dylib using the following code in the Objective-c class that needs to use the SQLite API
#import <sqlite3.h>
In general, we can use the third party database Fmdbdemo Open the use of the database, add header file
#import "FMDatabase.h"
(3), creating databases and tables
First you need to get the database storage path
nsstring* path = [Nshomedirectory () stringbyappendingpathcomponent:@ "Documents/data.db"];
_db = [[Fmdatabase alloc] initwithpath:path];
Then create the database:
//Open the database
BOOL res = [_db open];
if (res = = NO) {
NSLog (@ "Open failed");
return;
}
CREATE TABLE
res = [_db executeupdate:@ "CREATE table if not exists USER (name,image)"];
if (res = = NO) {
NSLog (@ "CREATE TABLE failed");
[_db close];
return;
}
Inserts the data
//nsnumber,nsstring,nsdata nsdata* the information
= Uiimagepngrepresentation (_imageview.image);
res = [_db executeupdate:@ insert INTO USER values (?,?), _namefield.text,data];
if (res = = NO) {
NSLog (@ "Insert data failed");
}
Closes the database
[_db close];
(4), delete data
BOOL res = [_db open];
if (res = = NO) {
NSLog (@ "Open failed");
return;
}
res = [_db executeupdate:@ "Delete from USER where name=?", _namefield.text];
if (res = = NO) {
NSLog (@ "Delete failed");
[_db close];
return;
}
NSLog (@ "Delete succeeded");
[_db Close];
(5), query data
BOOL res = [_db open];
if (res = = NO) {
NSLog (@ "Open failed");
return;
}
Query
fmresultset *set = [_db executequery:@ "select *from USER"];
while ([Set next]) {
//int
//int a = [set Intforcolumn:]
//nsnumber
//nsnumber* num = [Set OBJECTFORC Olumnname:]
nsstring *name = [set stringforcolumn:@ ' name '];
NSData *data = [set dataforcolumn:@ "image"];
NSLog (@ "name =%@", name);
}
[_db Close];
(6), modify the data
BOOL res = [_db open];
if (res = = NO) {
NSLog (@ "Open failed");
return;
}
NSData *data = uiimagepngrepresentation (_imageview.image);
Modify name;
res = [_db executeupdate:@ update USER set name=? Where Image=? ", _namefield.text,data];
Modify image
res = [_db executeupdate:@ update USER set image=? Where Name=? ", Data,_namefield.text];
if (res = = NO) {
NSLog (@ "Modify failed");
[_db close];
return;
}
NSLog (@ "modified successfully");
[_db Close];
Sixth. use of the core data framework
(1), Core data Introduction
Core data is a purely object-oriented framework that can be used to manage the persistence of associations between entities and entities-so-called persistence, meaning that core data can save entities to a persistent storage device or take them out when needed;
Core data can be persisted to the bottom of the SQLite database, can also be an XML document, or even directly in memory as a persistent storage (if you choose memory as a persistent memory device, then the application restart, the data will be lost);
Core data is an entity. An entity is a model object that is managed by the core data management, which must be an instance of the Nsmanagedobject class or its subclasses. There are 1-1,1-n,n-n associations between entities and entities, All entities of the application and associated relationships are called managed models (Nsmanagedobjectmodel);
The
Core data is the central object of the managed object context (Nsmanagedobjectcontext, sometimes referred to as the context), all entities are in managed object context management, the core data application to the entity of any increase, delete, change, All operations must be done through the managed object context. The key APIs in the
Core data application are as follows: ①, managed object Model (Nsmanagedobjectmodel): This object is responsible for managing all entities of the entire application and the association relationships between entities. When the developer uses the Xcode graphical interface to design the relationship between entity and entity, it is necessary to use the object to load and manage the application managed object model. ②, persistent storage Coordinator (Nspersistentstorecoordinator): Responsible for managing the underlying storage files, such as SQLite databases. ③, managed Object Context (Nsmanagedobjectcontext): This object is core data, the main object, the application of the entity to do the increase, delete, change, check operations need to be done through the object. ④, Entity description (Nsentitydescription): An object represents a descriptive information about an entity, which, to some extent, is equivalent to an abstraction of an entity. The entity description defines the name of the entity, the implementation class for the entity, and a collection that defines all the attributes that the entity contains. ⑤, crawl request (Nsfetchrequest): This object encapsulates the query entity's request, including the program needs to query those entities, query conditions, collation, and so on. The crawl request defines the entity name of the query, the query criteria for the crawl request (represented by the nspredicate), And a Nsarray set defines all the sorting rules;
The steps for using the core data persistence operation are roughly as follows: Creating a Nsmanagedobjectmodel object to load the managed object model of the management application; , based on the Nsmanagedobjectmodel object, the Nspersistentstorecoordinator object is created according to the actual need, which determines the storage form of core data. , based on the Nsmanagedobjectmodel object, the Nsmanagedobjectcontext is created, which is the core object of the persistent access of core data. , for ordinary add, delete, change, check operations, you need to create new entities, delete entities, modify entities, and then call the Nsmanagedobjectcontext object's Save: method to save these modifications on the underlying storage device. , if you want to execute the query, you need to create the Nsfetchrequest object before you call Nsmanagedobjectcontext's Executefetchrequest:error: method to execute the query, This method returns the Nsarray of all the entities that match the criteria. (2) Initialization of core data project
The steps are as follows:
①, add coredata.framework frame for the item;
②, create a "Data Model" file;
③, initialization of core data applications must be key API objects: Nsmanagedobjectmodel, Nspersistentstorecoordinator, Nsmanagedobjectcontext.
For example, these core API objects are all objects that are globally available, so programs typically perform initialization in the application delegate class:
The interface part of the application delegate class:
#import <UIKit / UIKit.h>
#import <CoreData / CoreData.h>
@interface AppDelegate: UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow * window;
@property (strong, nonatomic, readonly) NSManagedObjectModel * managedObjectModel;
@property (strong, nonatomic, readonly) NSManagedObjectContext * managedObjectContext;
@property (strong, nonatomic, readonly) NSPersistentStoreCoordinator * persistentStoreCoordinator;
@end
Application interface delegate class implementation part
@synthesize managedObjectContext = _managedObjectContext;
@synthesize manageObjectModel = _manageObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
-(void) saveContext {
NSError * error = nil;
// Get the context of the managed object of the application
NSManagedObjectContext * managedObjectContext = self.managedObjectContext;
if (managedObjectContext! = nil) {
// If the managed object context contains unsaved modifications, the save is performed, and if the save fails, an error message is recorded
if ([managedObjectContext hasChanges] &&! [managedObjectContext save: & error]) {
NSLog (@ "Save error:% @,% @", error, [error userInfo]);
}
}
}
// Managed objects
-(NSManagedObjectModel *) managedObjectModel
{
// If _managedObjectModel has been initialized, then return the object directly
if (_managedObjectModel! = nil) {
return _managedObjectModel;
}
// Get the NSURL of the entity model file object
NSURL * modelURL = [[NSBundle mainBundle] URLForResource: @ "User" withExtension: @ "momd"];
// Load the entity model file of the application and initialize the NSManagedObjectModel object
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL: modelURL];
// _managedObjectModel = [NSManagedObjectModel mergedModelFromBundles: nil];
return _managedObjectModel;
}
// Persistent storage coordinator
-(NSPersistentStoreCoordinator *) persistentStoreCoordinator {
// If _persistentStoreCoordinator has been initialized, then return the object directly
if (_persistentStoreCoordinator! = nil) {
return _persistentStoreCoordinator;
}
// Get the storage directory of the SQLite database file
NSURL * storeURL = [[self applicationDocumentDirectory] URLByAppendingPathComponent: @ "Books.sql