IOS data persistence (1): ios data

Source: Internet
Author: User

IOS data persistence (1): ios data

1. What is data persistence?

Data Persistence and permanent storage of data save the data in the hard disk, close the program, release the memory, re-open the program, you can continue to access the previously stored data.

Ii. Data Persistence

Common Data Persistence methods include the following:

Sandbox

Preference

Archive/archive

SQLite

CoreData

This article only talks about sandbox, preference, archiving/anti-archiving.

1. Sandbox

Sandbox is the name of a specific folder generated by the system for each application. The folder name consists of hexadecimal data. The Sandbox file names of each application are different, is randomly generated by the system.

// Obtain the main directory NSString * path = NSHomeDirectory (); NSLog (@ "% @", path );

The path and function of each folder in the sandbox

// Some important files stored by Documents, but the files stored in Documents cannot be too large // how to obtain the Documents file directory NSString * documentsPath = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) firstObject]; NSLog (@ "% @", documentsPath); // The value of firstobject is because this method is initially developed using mac OS X. for PC users, multiple users can, therefore, you can obtain the path of many users. However, this method is currently used for mobile phone development. There is only one user on the mobile phone end. Therefore, only one user can be obtained, and the lastobject can also be used. // Library: A resource Library that stores less important data, which is relatively larger and contains two subfolders. NSString * libraryPath = [NSSearchPathForDirectoriesInDomains (NSLibraryDirectory, NSUserDomainMask, YES) firstObject]; // Caches: cached files, image Caches, audios, and videos. Webpage resources. The application clears the cache, that is, the NSString * cachesPath = [NSSearchPathForDirectoriesInDomains (NSCachesDirectory, NSUserDomainMask, YES) firstObject]; // Preferences: System Preferences, setting of the corresponding program, for example, the user name and password cannot be found in the preference path. You can use NSUserDefaults/temp to store temporary files, such as the downloaded zip package, decompress the package and delete NSString * tempPath = NSTemporaryDirectory (); NSLog (@ "% @", tempPath); // bundle: Before ios8, package and shahe are in the same directory, and then. the app is stored in an independent file directory. The. app file readOnly. This package is downloaded from the appStore. This package is also NSString * bundlepath = [[NSBundle mainBundle] bundlePath] When the program is uploaded. NSLog (@ "% @", bundlepath );
// NSSearchPathDirectory this class is used to find the file directory // The first parameter: file name // The second parameter, determine the search domain // The third parameter: determine whether the relative path is an absolute path. YES absolute, NO relative

File-related operations

/*** File Deletion */-(void) deleteFile {NSString * cachesPath = [Export (NSCachesDirectory, NSUserDomainMask, YES) firstObject]; NSString * imagePath = [cachesPath stringByAppendingPathComponent: @ "iamge"]; NSLog (@ "% @", imagePath); // create a file manager NSFileManager * fileManager = [NSFileManager defaultManager]; // determine whether the file exists BOOL isExist = [fileManager fileExistsAtPath: imagePath]; if (! IsExist) {BOOL isSuccess = [fileManager createDirectoryAtPath: imagePath withIntermediateDirectories: YES attributes: nil error: nil]; NSLog (@ "% @", isSuccess? @ "Created successfully": @ "failed to create");} // Delete the object if ([fileManager fileExistsAtPath: imagePath]) {BOOL isSucess = [fileManager removeItemAtPath: imagePath error: nil]; NSLog (@ "% @", isSucess? @ "Deletion successful": @ "deletion failed ");}}
/*** Move */-(void) moveFile {NSString * cachesPath = [callback (NSCachesDirectory, NSUserDomainMask, YES) firstObject]; NSString * imagePath = [cachesPath stringByAppendingPathComponent: @ "iamge"]; NSLog (@ "% @", imagePath); // create a file manager NSFileManager * fileManager = [NSFileManager defaultManager]; // determine whether the file exists BOOL isExist = [fileManager fileExistsAtPath: imagePath]; if (! IsExist) {BOOL isSuccess = [fileManager createDirectoryAtPath: imagePath withIntermediateDirectories: YES attributes: nil error: nil]; NSLog (@ "% @", isSuccess? @ "Created successfully": @ "failed to create");} // delete a file // if ([fileManager fileExistsAtPath: imagePath]) {// BOOL isSucess = [fileManager removeItemAtPath: imagePath error: nil]; // NSLog (@ "% @", isSucess? @ "Deletion successful": @ "deletion failed "); //} // copy the file // copy the plist file in the package to the NSString * plistInBundlePath = [[NSBundle mainBundle] pathForResource: @ "NB. plist "ofType: nil]; NSString * nBPath = [imagePath stringByAppendingPathComponent: @" NB. plist "]; // copy, if (! [FileManager fileExistsAtPath: nBPath]) {BOOL isSuccess = [fileManager copyItemAtPath: plistInBundlePath toPath: nBPath error: nil]; NSLog (@ "% @", isSuccess? @ "Successful copy": @ "failed copy");} NSString * toPath = [Response (NSDocumentDirectory, NSUserDomainMask, YES) firstObject]; BOOL isSuccess = [fileManager moveItemAtPath: nBPath toPath: [toPath stringByAppendingPathComponent: @ "NB. plist "] error: nil]; NSLog (@" % @ ", isSuccess? @ "Successfully moved": @ "failed to move ");}
// String Write File-(void) writeToFile {// simple object Write File: String, array, dictionary, binary stream only supports writing files to these simple objects. // if you want to write data to a file, the dictionary must ensure the array. The data in the dictionary is also a simple object (if it is a complex object, refer to archive and archive later) // write the string to NSString * documentsPath = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) firstObject] in the Documents folder; NSString * toPath = [documentsPath stringByAppendingPathComponent: @ "string.txt"]; NSString * string = @ "string- "; // The first parameter, the path of the file to be written. If no file exists, the second parameter is automatically created, atomicity, and whether a secondary file needs to be generated, protects the security of the third parameter in multi-thread mode. The fourth parameter in encoding format is the error message NSError * error = nil; BOOL isSuccess = [string writeToFile: toPath atomically: YES encoding: NSUTF8StringEncoding error: & error]; NSLog (@ "% @", isSuccess? @ "Write Succeeded": @ "Write failed"); NSString * str = [NSString stringWithContentsOfFile: toPath encoding: NSUTF8StringEncoding error: nil]; NSLog (@ "% @", str );}
// Array Write File-(void) writeArray {NSString * str = [NSSearchPathForDirectoriesInDomains (NSLibraryDirectory, NSUserDomainMask, YES) firstObject]; NSString * toPath = [str stringByAppendingPathComponent: @ "array.txt"]; NSArray * array = @ [@ "123", @ "123"]; BOOL isSuccess = [array writeToFile: toPath atomically: YES]; NSLog (@ "% @", isSuccess? @ "Write Succeeded": @ "Write failed"); NSArray * arr = [NSArray arrayWithContentsOfFile: toPath]; NSLog (@ "% @", arr );}
// Dictionary Write File-(void) writeDic {NSDictionary * dic =@{ @ "key": @ "value"}; NSString * str = [NSSearchPathForDirectoriesInDomains (NSCachesDirectory, NSUserDomainMask, YES) firstObject]; NSString * toPath = [str stringByAppendingPathComponent: @ "dictonry.txt"]; BOOL isSuccess = [dic writeToFile: toPath atomically: YES]; NSLog (@ "% @", isSuccess? @ "Success": @ "failed"); NSDictionary * dict = [NSDictionary dictionaryWithContentsOfFile: toPath]; NSLog (@ "% @", dict );}
// NSData Write File-(void) writeData {NSString * tempPath = NSTemporaryDirectory (); NSString * toPath = [tempPath stringByAppendingPathComponent: @ "data.txt"]; NSString * string = @ "datadata"; NSData * data = [string dataUsingEncoding: NSUTF8StringEncoding]; BOOL isSuccess = [data writeToFile: toPath atomically: YES]; NSLog (@ "% @", isSuccess? @ "Success": @ "failed"); NSData * getData = [NSData dataWithContentsOfFile: toPath]; NSString * str = [[NSString alloc] initWithData: getData encoding: NSUTF8StringEncoding]; NSLog (@ "% @", str );}

2. preference

// Preference-(void) writeToPreference {// NSUserDefaults inherits from NSObject, And the singleton assigns NSLog values in kvc mode (@ "% @", NSHomeDirectory ()); // create the user index object NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults]; [defaults setInteger: 100 forKey: @ "money"]; // After the file in preference is modified, the [defaults synchronize]; NSInteger money = [defaults integerForKey: @ "money"] is synchronized immediately. NSLog (@ "% ld", money); [defaults setInteger: 10000 forKe Y: @ "MyMoney"]; [defaults synchronize]; NSInteger you = [defaults integerForKey: @ "you"]; NSLog (@ "% ld", (long) you ); if (money <10) {NSLog (@ "there is no money");} else {NSLog (@ "-100"); money-= 100; [defaults setInteger: 40 forKey: @ "money"]; [defaults setInteger: 1000 forKey: @ "YourMoney"];} // NSUserDefaults generally stores small amounts of data, mostly used to store values // example: Determine whether the user logs on to NSUserDefaults * userDefault = [NSUserDefaults standa for the first time RdUserDefaults]; BOOL isFirst = [userDefault boolForKey: @ "isFirst"]; [userDefault setBool: YES forKey: @ "isFirst"]; [userDefault synchronize]; if (! IsFirst) {NSLog (@ "First Login");} else {NSLog (@ "not the First Login ");}}

3. Archive/archive

Archive is required for writing complex objects to files. archive is required for reading complex objects. Files cannot be written directly. Archive/archive is also required for storing complex objects in arrays.

Complex objects use row archiving and reverse archiving. They must follow the NSCoding Protocol and implement the Protocol-(void) encodeWithCoder :( NSCoder *) ACO;-(id) initWithCoder :( NSCoder *) aDecoder; two methods

 

Create Person class

Follow the protocol in Person. h

/// Person. h // 07.24-DataPersistiser /// Created by lanouhn on 14/7/24. // Copyright (c) 2014 LCD. all rights reserved. // # import <Foundation/Foundation. h> @ interface Person: NSObject <NSCoding> @ property (nonatomic, copy) NSString * name; @ property (nonatomic, copy) NSString * gender; @ property (nonatomic, assign) NSInteger age; @ end

Implement protocol methods in Person. m

/// Person. m // 07.24-DataPersistiser /// Created by lanouhn on 14/7/24. // Copyright (c) 2014 LCD. all rights reserved. // # import "Person. h "@ implementation Person // when the object is to be archived, this method is automatically triggered by the object-(void) encodeWithCoder :( NSCoder *) acder {[ACO encodeObject: self. name forKey: @ "name"]; [ecoder encodeObject: self. gender forKey: @ "gender"]; [ecoder encodeObject: @ (self. age) forKey: @ "age"];}-(id) initWithCoder :( NSCoder *) aDecoder {self = [super init]; if (self) {self. name = [aDecoder decodeObjectForKey: @ "name"]; self. gender = [aDecoder decodeObjectForKey: @ "gender"]; self. age = [[aDecoder decodeObjectForKey: @ "age"] integerValue];} return self ;}@ end

Archive/archive

-(Void) archiver {// writes a complex file into a file and first converts it to an nsdata object // archive: the essence of archive is to put other types of data (person ), first convert to NSData and then write the file. Person * person = [[Person alloc] initWithName: @ "rose" gender: @ "girl" age: 25]; // NSKeyedArchiver compression tool class, inherited from NSCoder, it is mainly used to encode NSMutableData * data = [NSMutableData data]; NSKeyedArchiver * achiver = [[NSKeyedArchiver alloc] encoding: data]; // use a compression tool to press Person to data [achiver encodeObject: person forKey: @ "person"]; // complete compression. Stop the compression tool [achiver finishEncoding]; NSString * homePath = NSHomeDirecto Ry (); NSString * toPath = [homePath stringByAppendingPathComponent: @ "person.txt"]; BOOL isSuccess = [data writeToFile: toPath atomically: YES]; NSLog (@ "% @", isSuccess? @ "Successful": @ "failed"); // read complex objects, reverse archiving // NSKeyedUnarchiver NSData * getData = [NSData dataWithContentsOfFile: toPath]; optional * unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData: getData]; // extract Person * p1 = [unArchiver decodeObjectForKey: @ "person"]; [unArchiver finishDecoding];}
// Set NSArray NSDictionary if you want to archive and archive, the elements stored in it must also follow the NSCoding protocol Person * person1 = [[Person alloc] initWithName: @ "jack" gender: @ "male" age: 20]; Person * person2 = [[Person alloc] initWithName: @ "rose" gender: @ "female" age: 20]; NSArray * array = @ [person1, person2]; NSMutableData * data = [NSMutableData data]; NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc] encoding: data ]; Object: array forKey: @ "array"]; [archiver finishEncoding]; NSString * tmpPath = NSTemporaryDirectory (); NSString * toPath = [tmpPath stringByAppendingString: @ "array.txt"]; BOOL isSuccess = [data writeToFile: toPath atomically: YES]; NSLog (@ "% @", isSuccess? @ "Success": @ "failed"); // archive NSKeyedUnarchiver * unArchiver = [[initalloc] initForReadingWithData: data]; NSArray * unArchiverArray = [unArchiver decodeObjectForKey: @ "array"];

 

 

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.