IOS ui16_data persistence

Source: Internet
Author: User

IOS ui16_data persistence

//// Student. h // ui16_data persistence /// Created by dllo on 15/8/19. // Copyright (c) 2015 zhozhicheng. all rights reserved. // # import
  
   
# Pragma mark if you want to implement archiving and anti-archiving operations, you must first sign an agreement NSCoding @ interface Student: NSObject
   
    
@ Property (nonatomic, copy) NSString * name; @ property (nonatomic, copy) NSString * sex; @ property (nonatomic, assign) NSInteger age; @ property (nonatomic, copy) NSString * holobby; // for these four attributes, write a custom initialization method and constructor-(instancetype) initWithName :( NSString *) name sex :( NSString *) sex age :( NSInteger) age holobby :( NSString *) holobby; + (instancetype) studentWithName :( NSString *) name sex :( NSString *) sex age :( NSInteger) age holobby :( NSString *) holobby; @ end
   
  
//// Student. m // ui16_data persistence /// Created by dllo on 15/8/19. // Copyright (c) 2015 zhozhicheng. all rights reserved. // # import Student. h @ implementation Student-(instancetype) initWithName :( NSString *) name sex :( NSString *) sex age :( NSInteger) age holobby :( NSString *) holobby {self = [super init]; if (self) {_ age = age; _ name = name; _ holobby = holobby; _ sex = sex;} return self ;}+ (instancetype) studentWithName :( NSString *) name sex :( NSString *) sex age :( NSInteger) age holobby :( NSString *) holobby {Student * stu = [[Student alloc] initWithName: name sex: sex age: age holobby: holobby]; return stu ;}# after signing the NSCoding protocol, pragma mark must implement two protocol methods, one of which is used for archiving, -(void) encodeWithCoder :( NSCoder *) acder {[acder encodeObject: self. name forKey: @ name]; [aCoder encodeInteger: self. age forKey: @ age]; [ecoder encodeObject: self. holobby forKey: @ hobbies]; [acder encodeObject: self. sex forKey: @ gender]; // use the encode method to match with the Data Type}-(id) initWithCoder :( NSCoder *) aDecoder {self = [super init]; if (self) {// decompile the data back to self based on the previous key. name = [aDecoder decodeObjectForKey: @ name]; self. age = [aDecoder decodeIntegerForKey: @ age]; self. holobby = [aDecoder decodeObjectForKey: @ hobbies]; self. sex = [aDecoder decodeObjectForKey: @ gender];} return self;}-(void) didReceiveMemoryWarning {[super didreceivemorywarning]; // Dispose of any resources that can be recreated .} @ end
//// ViewController. m // ui16_data persistence /// Created by dllo on 15/8/19. // Copyright (c) 2015 zhozhicheng. all rights reserved. // # import ViewController. h # import Student. h @ interface ViewController () @ end @ implementation ViewController-(void) viewDidLoad {[super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. // In order to ensure the absolute security of your data, the Apple mobile phone designed a sandbox file. Every application is equipped with its own sandbox file. Every run, folder The name will become a non-regular string // The first parameter: the folder to which you want to go, the NSDocuemtDirectory to the documents file, the 64-line folder, you can also go to the caches folder, corresponding to 68 rows // The second parameter: the type of the accessed folder. Specify that the access is a user folder // The third parameter: absolute path (YES), relative path (NO) // The absolute path is used by the system. The system can find the folder based on the current path. When operating on the folder, the absolute path // relative path will only display the folder to be accessed, other parts are ~, Tell the programmer which folder to go // NSArray * sandbox = NSSearchPathForDirectoriesInDomains (NSCachesDirectory, NSUserDomainMask, YES); // NSLog (@ % @, sandbox [0]); // There are three files in the sandbox. // 1. is the Documents file: it is mainly used to store the user's desired information, such as the collected information or some content set by the user, therefore, the favorites function is to write files in this folder // 2. the Library folder is convenient for program developers. It mainly operates on two folders, caches and Preferences // caches, which are used to save cached files. SDWebImage adds images to cached files, so the clear cache function is to delete this folder // Preferences: Generally, it is used to save the information set by the programmer. For example, NSUserDefults will save the data in this folder. // 3. tmp file: the temporary content is generally stored. // There is another file in the sandbox before. app file, which has been removed in the new version // write simple objects to the local device. Simple objects refer to NSString, NSArray // 1. obtain the sandbox path through the array // NSArray * sandbox = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES ); //// obtain the sandbox path from the array // NSString * sandBoxPath = sandbox [0]; // concatenate a path to the file to be written, there are two splicing methods: // NSString * documentPath = [sandBoxPath stringByAppendingString: @/Gu yu.txt]; // NSString * documentPath = [sandBoxPath stringByAppendingPathComponent: @ Gu Yu. xml]; // NSLog (@ % @, documentPath); // NSString * str = @ Shushan has a path of diligence, and has no difficulties in learning the sea; //// write the string to the local device /// the first parameter: The Path to save the file /// the second parameter: file Protection YES // The third parameter: encoding // The fourth parameter, error message // [str writeToFile: documentPath atomically: YES encoding: NSUTF8StringEncoding error: nil]; // if there is a corresponding file under the path, the original file will be overwritten, if not, create a new file. // read the sandbox file. // NSString * temoStr = [NSString stringWithContentsOfFile: documentPath encoding: NSUTF8StringEncoding error: nil]; // NSLog (@ % @, temoStr); // write the array to the local device. // NSArray * arr = @ [@ 1, @ 2, @ 3, @ 4, @ 5, @ 6]; // obtain the sandbox address through arrays // NSArray * sandbox = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES ); //// Save the sandbox path with a string // NSString * sandboxPath = sandbox [0]; //// splicing path for the file to be written // NSString * documentPath = [sandboxPath stringByAppendingPathComponent: @ haha. plist]; // write the array to the local device. // [arr writeToFile: documentPath atomically: YES]; // NSLog (% @, documentPath ); ///// read the array // NSArray * temp = [NSArray arrayWithContentsOfFile: documentPath]; // NSLog (@ % @, temp ); /// write the dictionary to the local computer. // NSDictionary * dic = [NSDictionary dictionary: @ 1, @ 2, nil]; // NSArray * sandbox = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); // NSString * sandboxPath = sandbox [0]; // NSString * documentPath = [sandboxPath stringByAppendingPathComponent: @ ]; // [writeToFile: documentPath atomically: YES]; // NSLog (@ % @, documentPath); // NSDictionary * temp = [NSDictionary dictionaryWithContentsOfFile: documentPath]; // NSLog (@ % @, temp ); // write a complex object to the local disk, which means that the object we created is written to the local disk, also called archive and archive operations // create objects // Student * stu1 = [Student studentWithName: @ John sex: @ male age: 14 Hoby: @ Play]; /// 1. obtain the sandbox path through the array // NSArray * sandbox = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); // 2. use a string to capture the sandbox path // NSString * sandBoxPath = sandbox [0]; // 3. concatenate the folder path. The folder extension is any // NSString * decomentPath = [sandBoxPath stringByAppendingPathComponent: @ student. avi]; // archive the object /// the first parameter: the object to be archived /// the second parameter: path // [NSKeyedArchiver archiveRootObject: stu1 toFile: decomentPath]; // NSLog (@%@, decomentPath); // // Student * newStu = [NSKeyedUnarchiver unarchiveObjectWithFile: decomentPath]; // NSLog (% @, newStu. name); // create three students // Student * stu1 = [Student studentWithName: @ John sex: @ male age: 14 holobby: @ Play]; // Student * stu2 = [Student studentWithName: @ Li Si sex: @ female age: 15 holobby: @ sleep]; // Student * stu3 = [Student studentWithName: @ Shen 6 sex: @ male age: 16 holobby: @ singing]; // NSArray * array = @ [stu1, stu2, stu3]; // NSArray * sandbox = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, 1, YES); // NSString * sandboxPath = sandbox [0]; // concatenate the file path // NSString * documentPath = [sandboxPath stringByAppendingPathComponent: @ Cao Jun. plist]; // archive operation // [NSKeyedArchiver archiveRootObject: array toFile: documentPath]; // NSLog (@ % @, documentPath ); ///// archive, traverse the Student name // NSArray * arr = [NSKeyedUnarchiver unarchiveObjectWithFile: documentPath]; // for (Student * temp in arr) {// NSLog (% @, temp. name); //} # warning Summary: Data Persistence steps // 1. specify the folder to go to // 2. use a string to receive the path // 3. splicing file path // 4. write local or archive operations // note; for complex object archiving, sign the NSCoding Protocol and implement two protocol methods, to archive complex objects in the array, you must also sign the Protocol // NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults]; // [defaults setObject: @ 123456 forKey: @ password]; // NSArray * sandBox = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, 1, YES); // NSLog (@ % @, sandBox [0]); // NSLog (@ % @, [defaults objectForKey: @ password]); // NSUserDefaults generally stores small data, such as strings, its usage is similar to that in the dictionary. // the File Manager operates the folder NSArray * sandBox = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, 1, YES); NSString * sandBoxPath = sandBox [0]; // create a file manager NSFileManager * manager = [NSFileManager defaultManager]; // concatenate a path NSString * filePath = [sandBoxPath stringByAppendingPathComponent: @ guyu] For the folder to be created; // No extension is required for the folder name. // create a folder using manager [manager createDirectoryAtPath: filePath withIntermediateDirectories: YES attributes: nil error: nil]; NSLog (@ % @, filePath); // write a string NSString * documentPath = [filePath stringByAppendingPathComponent: @ program string .txt] To the folder; NSString * str = @ I am a string; [str writeToFile: documentPath atomically: YES encoding: NSUTF8StringEncoding error: nil]; // remove the folder // [manager removeItemAtPath: filePath error: nil]; // clear the cache NSArray * cache = NSSearchPathForDirectoriesInDomains (NSCachesDirectory, 1, YES); NSString * cachePath = cache [0]; [manager removeItemAtPath: cachePath error: nil];}

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.