IOS Data storage

Source: Internet
Author: User

Data storage in iOS is generally divided into the following ways

1, XML attribute list (plist) archive 2, preference (preferences) 3, Nskeyedarchiver Archive (nscoding) 4, SQLite35, Core data vulgar talent sparse, first pull the first three kinds of storage method, Make a summary for review use 1, first understand the concept of sandbox, he is the application of the system folder, each application of the sandbox is independent of each other, can not access each other (IOS8 broke this practice). When it comes to data storage, it is not allowed to account for where the data is stored, typically stored in several files in the sandbox: Documents: Saves data that needs to be persisted when the app runs, and the directory is backed up when itunes synchronizes the device. For example, a game app can save a game archive in that directorytmp: Saves the temporary data required to run the app, and then deletes the corresponding file from the directory when it is finished. When the app is not running, the system may also purge files in that directory. itunes does not back up this directory when syncing the devicelibrary/caches: Saves data that needs to be persisted when the app runs, and itunes syncs the device without backing up the directory. Non-critical data with large storage volumes and no backup requiredlibrary/preference: Save all your app's preferences, and the iOS settings (settings) app will find the app's settings in that directory. This directory is backed up when itunes syncs the devicenext try to store the data in documents, there are two ways to get a documents directory:

1, NSString *home = Nshomedirectory();

2, NSString *doc = [nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, YES) lastobject];

Method 1 Gets the application sandbox directory, and further needs to use the Stringbyappendingstring method to stitch up the final path of documents, which is a bit cumbersome. Apple gives me a second kind of relatively good method, get to is an array object, in fact, inside a folder, arbitrarily lastobject or firstobject can be reliable to get, splicing a file to be stored to the name, write directly into, directly look at the code of the younger brother:

?
1 2 3 4 5 6 7 NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];     // 拼接文件路径     NSString *path = [doc stringByAppendingPathComponent:@"abc.plist"]     ;    NSArray *arr = @[@"luseike", @"25"];     [arr writeToFile:path atomically:YES];

There have been abc.plist in documents (the Plist file, which you must know, is essentially an XML file). The plist file can store some of the data types that the system comes with, such as Nsarray, NSString, NSNumber ..., which is the object with the WriteToFile method)

2. Try the second storage method, preference is designed to store the configuration information of the application. If you use preferences in the system to store data, the default is the preference folder in the store, and all the data is saved to the same file.

Its specific use is to use the Nsuserdefaults object, each application has its own userdefault, the code is as follows:

?
1 2 3 4 5 6 7 // 获取NSUserDefaults对象     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];     // 保存数据(如果设置数据之后没有同步, 会在将来某一时间点自动将数据保存到Preferences文件夹下面)     [defaults setObject:@"luseike" forKey:@"name"];     [defaults setObject:@"man" forKey:@"gender"];     [defaults setInteger:13 forKey:@"age"];     [defaults setDouble:10.1 forKey:@"height"];

Preference the data stored below is not immediately updated, you can manually sync under, [Defaults synchronize]; Easy to handle. Save the time is set in, read the time of course to follow this routine to do, on the code:

?
1 2 3 4 5 6 7 // 1.获取NSUserDefaults     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];     // 2.通过NSUserDefaults获取保存的数据     NSString *name = [defaults objectForKey:@"name"];     int age = [defaults integerForKey:@"age"];     NSLog(@"%@", name);     NSLog(@"%d", age);

Apple actually gave us the integerforkey, of course, there are floatfor, doublefor ...

3, the above both methods can only store the system's own data type, if you want to save our custom data type, it is a little awkward, it has to be evil to move out of the third Way

Nskeyedarchiver, this dude's a great guy. Customize a person class with name, age, and height three properties to see how nskeyedarchiver is stored

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 // 1.创建对象     /*     NJPerson *p = [[NJPerson alloc] init];     p.name = @"lnj";     p.age = 28;     p.height = 1.76;      */         NJStudent *stu = [[NJStudent alloc] init];     stu.name = @"luseike";     stu.age = 25;     stu.height = 1.8;     stu.weight = 60;          // 2.获取文件路径     NSString *docPath =  [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];     NSString *path = [docPath stringByAppendingPathComponent:@"stu.xxoo"];     NSLog(@"path = %@", path);         // 3.将自定义对象保存到文件中 //    [NSKeyedArchiver archiveRootObject:p toFile:path];     [NSKeyedArchiver archiveRootObject:stu toFile:path];

In this way, there is a condition that the type to be stored must implement the two methods defined in the Nscoding protocol, which describe how to store the data

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 // 当将一个自定义对象保存到文件的时候就会调用该方法 // 在该方法中说明如何存储自定义对象的属性 // 也就说在该方法中说清楚存储自定义对象的哪些属性 - (void)encodeWithCoder:(NSCoder *)encoder {     NSLog(@"NJPerson encodeWithCoder");     [encoder encodeObject:self.name forKey:@"name"];     [encoder encodeInteger:self.age forKey:@"age"];     [encoder encodeFloat:self.height forKey:@"heigth"]; }// 当从文件中读取一个对象的时候就会调用该方法 // 在该方法中说明如何读取保存在文件中的对象 // 也就是说在该方法中说清楚怎么读取文件中的对象 - (id)initWithCoder:(NSCoder *)decoder {     NSLog(@"NJPerson initWithCoder");     if (self = [super init]) {         self.name = [decoder decodeObjectForKey:@"name"];         self.age = [decoder decodeIntegerForKey:@"age"];         self.height = [decoder decodeFloatForKey:@"heigth"];     }     return self; }

It is also important to note that if a class inherits the person class, the attributes added in the subclass are not saved successfully, and the subclass must override the Protocol method. For example, defines the student class that inherits the person class, adds the weight property, and student implements the protocol code as follows

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 - (void)encodeWithCoder:(NSCoder *)aCoder {     [super encodeWithCoder:aCoder];     NSLog(@"NJStudent encodeWithCoder");     [aCoder encodeFloat:self.weight forKey:@"weight"]; }- (id)initWithCoder:(NSCoder *)aDecoder {     if (self = [super initWithCoder:aDecoder]) {         NSLog(@"NJStudent initWithCoder");         self.weight = [aDecoder decodeFloatForKey:@"weight"];     }     return self; }

And then save the student in the same way as the person who saved it.

First hooves so many, after learning new knowledge to add, novice learning, do not shoot bricks, to be continued ...

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.