Data Persistence UI pro in iOS _ 17

Source: Internet
Author: User

Data Persistence UI pro in iOS _ 17

The essence of data persistence is to write data from the inside to the local (hard disk), and write the data to the sandbox folder in iOS;

Sandbox mechanism: manages local files of applications in the form of sandbox folders, and the names of sandbox folders are randomly allocated and named in hexadecimal format;

 

=================================== About the sandbox directory ============== ==================

Internal Structure of sandbox:

Test sandbox:

Attribute:

 

@interface ViewController ()@property (retain, nonatomic) IBOutlet UITextField *nameField;@property (retain, nonatomic) IBOutlet UITextField *passwordField;@property(nonatomic,retain)NSUserDefaults *user;@end

 

// Login button

-(IBAction) handleLgin :( UIButton *) sender {// retrieve the data NSString * name = self in the input box. nameField. text; NSString * password = self. passwordField. text; // retrieve the NSString * pName = [self. user valueForKey: @ name]; NSString * pPassword = [self. user valueForKey: @ password]; // when the entered content is consistent with the information stored locally, the logon is successful if ([name isEqualToString: pName] & [password isEqualToString: pPassword]) {NSLog (@ login successful);} else {NSLog (@ Login Failed, please register );}}

// Registration button

-(IBAction) handleRegister :( UIButton *) sender {NSString * name = self. nameField. text; NSString * password = self. passwordField. text; // if (name. length = 0 | password. length = 0) {NSLog (@ account name or password is blank, registration failed !); Return;} // set the user name and password in the local file // set the user name [self. user setObject: name forKey: @ name]; // set the user Password [self. user setObject: password forKey: @ password]; // synchronize data [self. user synchronize]; NSLog (@ registered successfully );}
Remember to release:

 

- (void)dealloc {    [_nameField release];    [_passwordField release];    self.user = nil;    [super dealloc];}
Test results:

 

------------------------


 

----------------------------

1. Obtain the path of the sandbox folder

The main directory of the NSHomeDirectory () sandbox file. In this folder, there are three files named Document, Libralay, and Tmp. The Library contains two files, Caches, Perference, the system helped us create five files and store them under the sandbox files. These five files cannot be deleted.

 

   NSLog(@%@,NSHomeDirectory());

 

Documents: stores important files with small file sizes. These files can have copies. This folder cannot contain too many items. Otherwise, the files will be rejected directly during AppStore upload, for example: database

Obtain the path of the Documents folder

The first parameter: the folder name is 64 rows.

Second parameter: Search domain with priority: users --> local --> network --> system

Third parameter: relative path or absolute path: YES absolute path. NO indicates relative path.

This method was first developed on MAC and can be used by many users on PC. Therefore, the returned value of this method is an array, but now this method is applied to mobile terminals (iOS terminals), and there is only one mobile user, so there is only one access path.

  NSString *documentsPath =   [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];    NSLog(@%@,documentsPath);

Library, which stores some less important files, which are relatively large and contain two subfiles

    NSString *libraryPath =   [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)lastObject];    NSLog(@%@,libraryPath);

Caches stores cached files, such as webpage caching, image caching, video caching, video caching, and clearing cache in applications.

// Obtain the Caches path

 

   NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];    NSLog(@%@,cachesPath);

 

// Perferences preference settings to store some user information

Note: The path cannot be found and can only be accessed through NSUserDefaults

 NSUserDefaults *user = [NSUserDefaults standardUserDefaults];

// Perferences stores plist files. When you set the key-value pair for the first time, the plist file will be created for you. If you set the value directly, the plist file does not exist.

Values and values:
// [User setBool: YES forKey: @ login]; // retrieve the BOOL value // BOOL isLogin = [user boolForKey: @ login]; // NSLog (@ % d, isLogin );

// Data types supported by NSUserDefaults: array, dictionary, string, data, number, bool, integer, etc.

// NSUserDefaults generally stores data of the numerical type and does not store large data.

// Simulate the startup User Guide Diagram

BOOL isFirstLogin = [user boolForKey: @ login]; if (NO = isFirstLogin) {NSLog (@ first startup); [user setBool: YES forKey: @ login]; [user synchronize]; // synchronize now} else {NSLog (@ not the first startup );}

// Temporary files stored in Tem, such as zip files, are deleted after being decompressed.

Obtain the Tem path

    NSTemporaryDirectory();    NSLog(@%@,NSTemporaryDirectory()

NSFileManager is a file management tool used to add, delete, and copy files. It inherits from NSObject.

NSFileManager is also a singleton class

 NSFileManager *fileManger = [NSFileManager defaultManager];

==================================== Create a file ================

List of common NSFileManager operations:

// Create a file av. text under the Document file

1. obtain the Documents path

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

2. Create the path of av. text

 

// Get what you get when splicing stringByAppendingFormat // get what you get when splicing stringByAppendingString // Add a vertex before the content spliced by stringByAppendingPathExtension // Add a vertex before the content spliced by stringByAppendingPathComponent/
    NSString *avPath =   [documentsPath stringByAppendingPathComponent:@av];    NSLog(@%@,avPath);

 

First, determine whether the file exists.

 

If ([fileManger fileExistsAtPath: avPath]) {NSLog (@ exists);} else {NSLog (@ does not exist); // create av. text File // The second parameter asks: if there is no folder in the path whether to automatically create BOOL isSuccss = [fileManger createDirectoryAtPath: avPath withIntermediateDirectories: YES attributes: nil error: nil]; if (isSuccss) {NSLog (@ created successfully);} else {NSLog (@ creation failed );}}

 

==================================== Delete an object ================

// Delete a folder

1. Check whether the folder to be deleted exists.

If ([fileManger fileExistsAtPath: avPath]) {// if yes, delete BOOL isSuccess = [fileManger removeItemAtPath: avPath error: nil]; NSLog (@ % @, isSuccess? @ Deletion successful: @ deletion failed );}

====================================== Copy a file ================

// Copy NB. plist to the AV folder

// NSBundle application package. The app we downloaded from the AppStore is this package.

// Obtain the path of the application package

// After iOS8.0, The **. app is stored in a file separately. ** The. app file can only be read and cannot be written. The package uploaded to the AppStore is the package.

  NSString *bundlePath = [[NSBundle mainBundle]bundlePath];    NSLog(@%@,bundlePath);
// 1. obtain NB. plist path NSString * nbPath = [[NSBundle mainBundle] pathForResource: @ NB. plist ofType: nil]; // 2. manufacturing moved to the AV folder under the sandbox Documents folder NB. plist NSString * desPath = [avPath stringByAppendingPathComponent: @ NB. plist]; // 3. copy an object if (! [FileManger fileExistsAtPath: desPath]) {// first parameter: path before copy // second parameter: location to be copied BOOL isSucess = [fileManger copyItemAtPath: nbPath toPath: desPath error: nil]; NSLog (@%@, isSucess? @ Copy successful: @ copy failed );}

==================================== Move the file ========================== ================

// Move from the AV folder to the Library folder // 1. move the previous path NSString * surcePath = desPath; // 2. path NSString * libraryPath = [NSSearchPathForDirectoriesInDomains (NSLibraryDirectory, NSUserDomainMask, YES) lastObject]; NSString * toPath = [libraryPath stringByAppendingPathComponent: @ NB. plist]; // move if (! [FileManger fileExistsAtPath: toPath]) {BOOL isSuccess = [fileManger moveItemAtPath: surcePath toPath: toPath error: nil]; NSLog (@ % @, isSuccess? @ Successful migration: @ failed to move);} // call the simple object to write and read [self simpleObjectWritwTpFileAndFromeFile]; // call the archive and archive files [self archiverAndArchiver];}

 

===================================== Write and read simple objects ================== ====================

// Simple objects refer to NSString, NSDictionary, NSData, and their subclasses.

// Note: the elements of the Set (NSArray, NSDictionary) must be the four basic data types mentioned above. You can directly write and read files without placing complex objects;

Writing and reading strings:

// 1. write the string to NSString * string = @ Xiao Han Ge zhenshuai; // 2. create a file text in the Documents folder. text NSString * textPath = [[NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent: @ text. text]; // NSLog (@%@, textPath); // 3. string write // The first parameter: the file path to be written // The second parameter: YES provides multi-threaded security protection, and NO provides security protection // The third parameter: encoding format: BOOL isSuccess = [string writeToFile: textPath atomically: YES encoding : NSUTF8StringEncoding error: nil]; NSLog (, isSuccess? @ Write successful: @ write failed); // 4. string reads data from the file // The first parameter: NSString * contentString = [NSString stringWithContentsOfFile: textPath encoding: NSUTF8StringEncoding error: nil]; NSLog (@ % @, contentString );

NSArray read and write:

 

// 1. prepare the array NSArray * array = @ [@ Xiao Han Ge, @ Cai Guoqing, @ Jay Chou]; // 2. write the array to the array in the caches folder. text NSString * arrayPath = [[NSSearchPathForDirectoriesInDomains (NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent: @ array. text]; // 3. the file written into the array is isSuccess in XML format = [array writeToFile: arrayPath atomically: YES]; NSLog (@%@, isSuccess? @ Array write success: @ array write failure); // NSArray * contentArray = [NSArray arrayWithContentsOfFile: arrayPath]; NSLog (@ % @, contentArray );

 

After NSDictionary is written and read, it is converted into xml format:

// 1. prepare the Dictionary NSDictionary * dic ={@ male: @ Xiaohan elder brother, @ Star: @ Cai Guoqing, @ President: @ Xi }; // create a Dictionary in the 2.tem folder. text File NSString * dictionaryPath = [NSTemporaryDirectory () stringByAppendingPathComponent: @ dictionary. text]; // 3. isSuccess = [dic writeToFile: dictionaryPath atomically: YES]; NSLog (@%@, isSuccess? @ Dictionary written successfully: @ dictionary written failed); // 4. dictionary read NSDictionary * contentDic = [NSDictionary dictionaryWithContentsOfFile: dictionaryPath]; NSLog (@ % @, contentDic );

NSData writing and reading:

NSString * dataString = @ I want to say to people around me that you should wash your feet; // 1. prepare NSData object NSData * data = [dataString dataUsingEncoding: NSUTF8StringEncoding]; // 2. write data to the library. text File NSString * dataPath = [[NSSearchPathForDirectoriesInDomains (NSLibraryDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent: @ data. text]; // 3. NSData writing isSuccess = [data writeToFile: dataPath atomically: YES]; NSLog (@%@, isSuccess ? @ NSData write successful: @ NSData write failed); // 4. NSData reading NSData * contentData = [NSData dataWithContentsOfFile: dataPath]; // transfers binary data to the string NSString * newString = [[[NSString alloc] initWithData: contentData encoding: NSUTF8StringEncoding] autorelease]; NSLog (, newString );

================================== Write and read complex objects ============== ====================

A complex object is a data class that does not exist in the Fundation framework, that is, the class we define ourselves. It is called a complex object. A complex object cannot be directly written to a file and must be used by some tools, NSKeyedArchiver (archive tool)

Archive and archive:

1. Create a complex object Person

Person. h

# Import
 
  
@ Interface Person: NSObject
  
   
// If You Want to archive and archive a complex object, the object must follow the NSCoding protocol-(void) encodeWithCoder: (NSCoder *) ACO; @ property (nonatomic, copy) NSString * name; // name @ property (nonatomic, copy) NSString * gender; // gender @ property (nonatomic, assign) NSInteger age; // age-(id) initWithName: (NSString *) name gender: (NSString *) gender age: (NSInteger) age; @ end
  
 

Person. m

 

# Import Person. h @ implementation Person-(void) dealloc {self. name = nil; self. gender = nil; [super dealloc];}-(id) initWithName: (NSString *) name gender: (NSString *) gender age: (NSInteger) age {if (self = [super init]) {self. name = name; self. age = age; self. gender = gender;} return self;}-(NSString *) description {return [NSString stringWithFormat: @ % @-% ld, _ name, _ gender, _ age] ;}// the archive protocol method-(void) encodeWithCoder: (NSCoder *) acder {// more than archive this object, its attributes must be archived, in this case, you need to encode the attributes of [ACO der encodeObject: self. name forKey: @ name]; [aCoder encodeObject: self. gender forKey: @ gender]; [ecoder encodeObject: @ (self. age) forKey: @ age];} // method of the anti-archive protocol-(id) initWithCoder :( NSCoder *) aDecoder {if (self = [super init]) {// decode self. name = [aDecoder decodeObjectForKey: @ name]; self. gender = [aDecoder decodeObjectForKey: @ gender]; self. age = [[aDecoder decodeObjectForKey: @ age] integerValue];} return self ;}@ end
Archive:
// 1. create a complex object Person * p1 = [[Person alloc] initWithName: @ Xiaohan gender: @ male age: 20] autorelease]; // 2. create an archive tool NSMutableData * data = [NSMutableData data]; NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData: data]; // 3. archive // The first parameter: the object to be archived // The second parameter: Give the archive object a key value as the identifier, it is convenient to retrieve the archive object [archiver encodeObject: p1 forKey: @ boyFriend]; // 4. archive [archiver finishEncoding]; // 5. release [archiver Release]; // 6. write the archived data file // to the NSString * personPath = [NSHomeDirectory () stringByAppendingPathComponent: @ person. text]; // 7. write the converted data into the file BOOL isSuccess = [data writeToFile: personPath atomically: YES]; NSLog (@%@, isSuccess? @ Write successful: @ write failed );

 

Archive:

NSData * contentData = [NSData dataWithContentsOfFile: personPath]; // 1. create an archive tool NSKeyedUnarchiver * unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData: contentData]; // 2. read the file (archive method is required) Person * p2 = [unArchiver decodeObjectForKey: @ boyFriend]; NSLog (@%@, p2); // 3. stop [unArchiver finishDecoding]; // 4. release [unArchiver release];

==================================== Combination of arrays and complex objects ================ ====================
Create an array:

 

Person * p3 = [[Person alloc] initWithName: @ Xiaomei gender: @ female age: 21]; Person * p4 = [[Person alloc] initWithName: @ Guo Meimei gender: @ female age: 19]; NSArray * pArray = @ [p3, p4]; [p3 release]; [p4 release];

 

// Note: to archive complex objects into arrays, the stored complex objects must follow the NSCoding protocol.

// Use archive to write arrays to files

// 1. create an archive tool NSMutableData * aData = [NSMutableData data]; NSKeyedArchiver * nArchvier = [[NSKeyedArchiver alloc] initForWritingWithMutableData: aData]; // 2. use the archive object to archive the array [nArchvier encodeObject: pArray forKey: @ array]; // 3. stop the archive tool [nArchvier finishEncoding]; // 4. release [nArchvier release];

// Write the file to the Documents folder, array. tet

 

NSString * arrayPath = [[NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent: @ array. text]; isSuccess = [aData writeToFile: arrayPath atomically: YES]; NSLog (@%@, isSuccess? @ Complex array write success: @ complex array write failure );

 

// Read complex arrays

// Read NSData * newData = [NSData dataWithContentsOfFile: arrayPath] from a complex array; // 1. create an archive tool NSKeyedUnarchiver * nUnarchvier = [[NSKeyedUnarchiver alloc] initForReadingWithData: newData]; // 2. use the key value to archive the object. NSArray * newArray = [nUnarchvier decodeObjectForKey: @ array]; // 3. stop the anti-archive tool [nUnarchvier finishDecoding]; // 4. release [nUnarchvier release]; NSLog (@%, newArray [0], newArray [1]);

 

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.