14. ios Data Access

Source: Internet
Author: User

14. ios Data Access

IOSApplicationCommon Data Storage Methods


LXML property list (plist) archive lPreference (preference setting) lNSKeyedArchiver archive (NSCoding) lSQLite3lCoreData


Application sandbox


L each iOS application has its own application sandbox (the application sandbox is the file system directory), which is isolated from other file systems. The application must be in its own sandbox. Other applications cannot access the sandbox.

L file system directory of the application sandbox, as shown in (assuming the application name is Layer)




The root path of the simulator application sandbox is: (apple is the user name, 6.0 is the Simulator version)

/Users/apple/Library/Application Support/iPhoneSimulator/6.0/Applications



Application sandbox Structure Analysis


L Application Package(Layer in) contains all resource files and executable files l Documents: Save the persistent data generated when the application is running. This directory is backed up when the iTunes synchronization device is running. For example, a game application can save the game archive in this directory. Tmp: Save the temporary data required for running the application, and then delete the corresponding files from this directory after use. When the application is not running, the system may also clear files in the directory. This directory is not backed up when the iTunes synchronization device is working. Library/Caches: Save the persistent data generated when the application runs. This directory is not backed up when iTunes synchronizes devices. Non-important data that generally has a large storage space and does not need to be backed up

L Library/Preference: Save all the app's preference Settings. The iOS Settings app searches for app Settings in this directory. This directory is backed up when the iTunes synchronization device is running.


Common methods for obtaining the sandbox directory


L Sandbox root directory: NSString * home = NSHomeDirectory();

L Documents(2 methods) u uses the sandbox root directory to splice the "Documents" String

NSString * home =NSHomeDirectory();

NSString * documents = [homeStringByAppendingPathComponent:@"Documents"];

// It is not recommended because the new version of the operating system may modify the directory name.

U uses the NSSearchPathForDirectoriesInDomains Function

// NSUserDomainMask indicates that it is found in the user folder

// YES indicates the Tilde "~" in the expanded path

NSArray * array = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, NO );

// In iOS, there is only one directory that matches the input parameters. Therefore, this set has only one element.

NSString * documents = [arrayobjectAtIndex: 0];


Common methods for obtaining the sandbox directory


L Tmp: NSString * tmp = NSTemporaryDirectory(); L Library/Caches(Two methods similar to those described in Documents) u Concatenates the "Caches" string u using the sandbox root directory and uses the NSSearchPathForDirectoriesInDomains function (change the 2nd parameters of the function to NSCachesDirectory)

L Library/Preference: Access the settings in this directory through the NSUserDefaults class



Attribute list


L The property list is an XML file.

L if the object is of the NSString, NSDictionary, NSArray, NSData, or NSNumber type, you can use writeToFile: atomically: to directly write the object to the attribute list file.



Attribute list-ArchiveNSDictionary


L archive an NSDictionary object to a plist attribute list

// Encapsulate data into a dictionary

NSMutableDictionary * dict = [NSMutableDictionary dictionary];

[Dict setObject: @ "hen" forKey: @ "name"];

[DictsetObject: @ "15013141314" forKey: @ "phone"];

[Dict setObject: @ "27" forKey: @ "age"];

// Persists the dictionary to the Documents/stu. plist file.

[DictwriteToFile: path atomically: YES];



Attribute list-ArchiveNSDictionary





Attribute list-RestoreNSDictionary


L read the attribute list and restore the NSDictionary object

// Read the contents of Documents/stu. plist and instantiate NSDictionary

NSDictionary * dict = [NSDictionarydictionaryWithContentsOfFile: path];

NSLog (@ "name: % @", [dictobjectForKey: @ "name"]);

NSLog (@ "phone: % @", [dictobjectForKey: @ "phone"]);

NSLog (@ "age: % @", [dictobjectForKey: @ "age"]);

L print the following information:


Attribute list-NSDictionaryStorage and reading process





Preference settings


L many iOS apps support preference settings, such as setting the user name, password, and font size, iOS provides a set of standard solutions to add preference settings to an application l each application has an NSUserDefaults instance to access preference settings l for example, save the username, font size, and whether to log on automatically

NSUserDefaults* Defaults = [NSUserDefaultsStandardUserDefaults];

[DefaultsSetObject: @ "Itcast" forKey: @ "username"];

[DefaultsSetFloat: 18.0 fforKey: @ "text_size"];

[DefaultsSetBool: YESforKey: @ "auto_login"];




Preference settings

L read the last saved settings

NSUserDefaults * defaults = [NSUserDefaultsstandardUserDefaults];

NSString * username = [defaultsStringForKey: @ "Username"];

FloattextSize = [defaultsFloatForKey: @ "Text_size"];

BOOLautoLogin = [defaultsBoolForKey: @ "Auto_login"];

L note: When UserDefaults is used to set data, it is not to write data immediately, but to regularly write data in the cache to the local disk based on the timestamp. Therefore, after the set method is called, data may be terminated without being written to the disk application. If the preceding problem occurs, you can call the synchornize method to forcibly write data.

[Defaults synchornize];



NSKeyedArchiver

L if the object is of the NSString, NSDictionary, NSArray, NSData, or NSNumber type, you can use NSKeyedArchiver to archive and restore the object. l not all objects can be archived directly using this method, only objects that comply with the NSCoding protocol can have two methods for the lNSCoding Protocol: u EncodeWithCoder:

This method is called every time an object is archived. Generally, this method specifies how to archive each instance variable in the object. You can use encodeObject: forKey: Method to archive instance variables.

U InitWithCoder:

This method is called every time an object is restored (decoded) from a file. The decodeObject: forKey method is used to decode the instance variable of the object.



NSKeyedArchiver-ArchiveNSArray




NSKeyedArchiver-ArchivePersonObject (Person. h)

@interface Person : NSObject
 
  @property (nonatomic, copy) NSString *name;@property (nonatomic, assign) int age;@property (nonatomic, assign) float height;@end
 

NSKeyedArchiver - Archive Person Object ( Person. m )

@implementation Person- (void)encodeWithCoder:(NSCoder *)encoder {    [encoder encodeObject:self.name forKey:@"name"];    [encoder encodeInt:self.age forKey:@"age"];    [encoder encodeFloat:self.height forKey:@"height"];}- (id)initWithCoder:(NSCoder *)decoder {    self.name = [decoder decodeObjectForKey:@"name"];    self.age = [decoder decodeIntForKey:@"age"];    self.height = [decoder decodeFloatForKey:@"height"];    return self;}- (void)dealloc {    [super dealloc];    [_name release];}@end

NSKeyedArchiver - Archive Person Object (encoding and decoding)

L archive (encoding)

Person * person = [[[Personalloc] init] autorelease];

Person. name = @ "MJ ";

Person. age = 27;

Person. height = 1.83f;

[NSKeyedArchiverarchiveRootObject: persontoFile: path];

L restoration (Decoding)

Person * person = [NSKeyedUnarchiverunarchiveObjectWithFile: path];


NSKeyedArchiver-Notes for archiving objects

L if the parent class also complies with the NSCoding protocol, note that u should add the following sentence to the encodeWithCoder: method:

[SuperencodeWithCode: encode];

Ensure that the inherited instance variables can also be encoded, that is, they can also be archived.

U should add the following sentence to the initWithCoder: method:

Self = [super initWithCoder: decoder];

Make sure that the inherited instance variables can also be decoded and restored.


NSData

L use the archiveRootObject: toFile: Method to directly write an object to a file, but sometimes you may want to write multiple objects to the same file, you must use NSData for archiving objects.

LNSData can provide temporary storage space for some data to be written to the file later, or store the file content read from the disk. You can use [NSMutableDatadata] to create a variable data space.


NSData-Archive2ItemsPersonObject To the same file

Archive (encoding) // create a new variable data zone NSMutableData * data = [NSMutableData]; // connect the data zone to an NSKeyedArchiver object NSKeyedArchiver * archiver = [[[NSKeyedArchiver alloc] initForWritingWithMutableData: data] autorelease]; // starts archiving objects, all archived data is stored in NSMutableData [archiver encodeObject: person1 forKey: @ "person1"]; [archiver encodeObject: person2 forKey: @ "person2"]; // After archiving is completed (this method must be called) [archiver finishEncoding]; // write the archived data to the file [data writeToFile: path atomically: YES];

NSData - Restore from the same file 2 Items Person Object

Restore (Decoding) // read data from the file NSData * data = [NSData dataWithContentsOfFile: path]; // based on data, resolved to an authorization object NSKeyedUnarchiver * unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData: data]; Person * person1 = [unarchiver decodeObjectForKey: @ "person1"]; person * person2 = [unarchiver decodeObjectForKey: @ "person2"]; // after recovery, [unarchiver finishDecoding];

Use archive for deep Replication

For example, if you perform deep replication on a Person object, // temporarily store the data NSData * data = [NSKeyedArchiver archivedDataWithRootObject: person1]; // parse data, generate a new Person object Student * person2 = [NSKeyedUnarchiver unarchiveObjectWithData: data]; // print the memory address NSLog (@ "person1: 0x % x", person1 ); // person1: 0x7177a60NSLog (@ "person2: 0x % x", person2); // person2: 0x7177cf0


SQLite3

LSQLite3 is an open-source embedded relational database with good portability, ease of use, and low memory overhead. lSQLite3 is of no type, this means that you can save any type of data to any field in any interest table. For example, the following table creation statements are valid:

Create table t_person (name, age );

To ensure readability, we recommend that you add the following field types:

Create table t_person (name text, age integer );

Five data types commonly used by lSQLite3: text, integer, float, boolean, blob

L to use SQLite3 in iOS, first add the library file libsqlite3.dylib and import the main header file




Create, open, and close a database

L create or open a database

// Path :~ /Documents/person. db

Sqlite3* Db;

Intresult =Sqlite3_open([Path UTF8String], & db );

L code parsing: usqlite3_open () will open the database based on the file path. If it does not exist, a new database will be created. If result is equal to constant SQLITE_ OKIndicates that the database usqlite3 * db is successfully opened: the path of an open database instance u database file must be passed in as a C string (rather than an NSString ).

L shut down the database: Sqlite3_close(Db );


RunIf no data is returnedSQLStatement


L execute the create table statement

Char * errorMsg; // used to store error messages

Char * SQL = "create table if notexists t_person (id integer primary key autoincrement, nametext, age integer );";

Intresult =Sqlite3_exec(Db, SQL, NULL, NULL, & errorMsg );

L code parsing: usqlite3_exec () can execute any SQL statement, such as table creation, update, insert, and delete operations. However, you generally do not need to execute the query statement because it does not return the queried data usqlite3_exec (). You can also execute the statement: ① enable transaction: begin transaction; ② rollback transaction: rollback;

③ Submit a transaction: commit;


Insert with placeholderData

Char * SQL = "insert into t_person (name, age) values (?, ?); "; Sqlite3_stmt * stmt; if (sqlite3_prepare_v2 (db, SQL,-1, & stmt, NULL) = SQLITE_ OK) {sqlite3_bind_text (stmt, 1," hen ",-1, NULL); sqlite3_bind_int (stmt, 2, 27);} if (sqlite3_step (stmt )! = SQLITE_DONE) {NSLog (@ "");} sqlite3_finalize (stmt); code parsing: sqlite3_prepare_v2 () The returned value is SQLITE_ OK, indicating that the SQL statement has been prepared successfully without syntax

Insert with placeholder Data


Usqlite3_bind_text (): Most of the binding functions have only three parameters. ① 1st parameters are sqlite3_stmt * type. ② 2nd parameters indicate the placeholder position. The first placeholder is 1, not 0 ③ 3rd parameters refer to the value to be bound by the placeholder ④ 4th parameters refer to the length of data transmitted in the 3rd parameters. For the C string, you can pass-1 to replace the string length. ⑤ 5th parameters are an optional function callback, which is generally used to complete memory cleanup after the statement is executed. usqlite_step (): Execute an SQL statement, if SQLITE_DONE is returned, the execution is successful.

Usqlite_finalize (): destroys the sqlite3_stmt * object


Query data

Char * SQL = "select id, name, age from t_person;"; sqlite3_stmt * stmt; if (sqlite3_prepare_v2 (db, SQL,-1, & stmt, NULL) = SQLITE_ OK) {while (sqlite3_step (stmt) = SQLITE_ROW) {int _ id = sqlite3_column_int (stmt, 0); char * _ name = (char *) sqlite3_column_text (stmt, 1 ); NSString * name = [NSString stringwithuf8string: _ name]; int _ age = sqlite3_column_int (stmt, 2); NSLog (@ "id = % I, name = % @, age = % I ", _ id, name, _ age) ;}} sqlite3_finalize (stmt); code parsing sqlite3_step () returns SQLITE_ROW to traverse a new record sqlite3_column _*() used to obtain the value of each field. The 2nd parameters are the index of the field, starting from 0.

CoreData



Model File



Model File




Model File




Model File




NSManagedObject

L objects retrieved from the database using Core Data are NSManagedObject objects by default. The working mode of lNSManagedObject is somewhat similar to that of NSDictionary objects. All object attributes usetValue: forKey are accessed through key-value pairs: storage property value (property name: key)

UvalueForKey: Get the property value (the property name is key)



CoreDataMain object




BuildCore DataContext

L load model files from application packages

NSManagedObjectModel* Model = [NSManagedObjectModelMergedModelFromBundles: Nil];

L input the model and initialize NSPersistentStoreCoordinator

NSPersistentStoreCoordinator* Psc = [[NSPersistentStoreCoordinator alloc]InitWithManagedObjectModel: Model] autorelease];

L construct the SQLite file path

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

NSURL * url = [NSURLFileURLWithPath: [DocsstringByAppendingPathComponent: @ "person. data"];


BuildCore DataContext

Add a persistent repository. Here, SQLite is used as the repository NSError * error = nil; NSPersistentStore * store = [psc addPersistentStoreWithType: NSSQLiteStoreType configuration: nil URL: url options: nil error: & error]; if (store = nil) {// directly throw an exception [NSException raise: @ "add database error" format: @ "% @", [error localizedDescription];} initialize the context and set the persistentStoreCoordinator attribute NSManagedObjectContext * context = [[NSManagedObjectContext alloc] init]; context. persistentStoreCoordinator = psc; // after use, you need to [context release];

Add data

Input context to create a Person object NSManagedObject * person = [NSEntityDescription insertNewObjectForEntityForName: @ "Person" inManagedObjectContext: context]; set the simple attribute [person setValue: @ "MJ" forKey: @ "name"]; [person setValue: [NSNumber numberWithInt: 27] forKey: @ "age"]; Input Context to create a Card object NSManagedObject * card = [NSEntityDescription insertNewObjectForEntityForName: @ "Card" inManagedObjectContext: context]; [card setValue: @ "4414241933432" forKey: @ "no"]; sets the relationship between Person and Card [person setValue: card forKey: @ "card"];

Add data

Use context objects to synchronize data to the persistent Storage Library NSError * error = nil; BOOL success = [context save: & error]; if (! Success) {[NSException raise: @ "database access error" format: @ "% @", [error localizedDescription];} // If You Want To update: you can synchronize the changed data to the database by calling [context save: & error] After modifying the object attributes.

Query data

Initialize a query request NSFetchRequest * request = [[NSFetchRequest alloc] init] autorelease]; set the object NSEntityDescription * desc = [NSEntityDescription entityForName: @ "Person" inManagedObjectContext: context]; Set sorting (by age in descending order) NSSortDescriptor * sort = [NSSortDescriptor sortDescriptorWithKey: @ "age" ascending: NO]; request. sortDescriptors = [NSArray arrayWithObject: sort]; set the condition filter (name like '% Itcast-1 %') NSPredicate * predicate = [NSPredicate predicateWithFormat: @ "name like % @", @ "* Itcast-1 *"]; request. predicate = predicate;

Execute the request NSError * error = nil; NSArray * objs = [context executeFetchRequest: request error: & error]; if (error) {[NSException raise: @ "query error" format: @ "% @", [error localizedDescription];} traverses data for (NSManagedObject * obj in objs) {NSLog (@ "name = % @", [obj valueForKey: @ "name"]}


Delete data

Input the object to be deleted [context deleteObject: managedObject]; synchronize the result to the database NSError * error = nil; [context save: & error]; if (error) {[NSException raise: @ "delete error" format: @ "% @", [error localizedDescription];}


OpenCore DataOfSQLLog output switch





<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + signature + CmyxyMjnzai5/Signature + Gy6dGvyv2 + 3b/Signature + signature/H6b/Signature + m/9 s/Co6zKtczl1Nq05sihyv2 + 3 bXEu/Shanghai + pgltzybzcm9 "http://www.2cto.com/uploadfile/Collfiles/20150127/2015012708395039.png" alt = "\">



CreateNSManagedObjectSubclass


CreateNSManagedObjectSubclass



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.