iOS four ways to store data and pros and cons

Source: Internet
Author: User
Tags sqlite database

iOS has four ways to use data storage frequently:
First method: Store configuration information with Nsuserdefaults
Nsuserdefaults is designed to store configuration information for devices and applications. It returns the default, and most frequently used, instance object through a factory method.

This object stores the configuration information of the user in the system, and the developer is able to make changes to the existing information through this instance object. You can also create new configuration items according to your needs.

He is actually a. plist file that is stored in a file sandbox, and is not encrypted by the system, only IOS6 is not stored in a frequently used document folder, so do not crack the system is not see the file. So the data stored in this method is not very, very secure, if you want to store security or rely on your own encryption algorithm. In general, this method stores a small amount of information, if it is stored in large quantities. If you store 100 data, how do you record key values? It can store data in whatever part of the code, and you don't know how much data your entire app stores, so it's not conducive to unified management. Not recommended for use. Is that you put the stored data functions uniformly in a file for easy management, but you can not guarantee that others will follow your will and practices ah. So it's better to store the other object in a better way.

All of the confidential data is stored in an object. I know it at a glance. Deleting and joining is easy and easy to manage. As a qualified code-farmer, don't say so much should and should not be, business logic decided not to have such a data so pale words. To eliminate all kinds of abnormal data from the mechanism. Such as: Object storage. The validity of the parameters is inferred at all function entrances.

+ (void)setUserDefaultsValue:(id)value key:(NSString *)key{    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];    [userDefaults setObject:value forKey:key];    [[NSUserDefaults standardUserDefaults] synchronize];}+ (id)objectForKey:(NSString *)key{    return [[NSUserDefaults standardUserDefaults] objectForKey:key];}

Call:
NSString *selectedkey = [[Nsuserdefaults standarduserdefaults] objectforkey:@ "Selectedkey"];

Another method: The method is stored with a CoreData object. Like MFC, which is called serialization and deserialization, MFC is actually stored in the appropriate database form for the application. He is actually putting the file in the file sandbox. The corresponding document folder, so the user can see the file. The file is encrypted by the system.

The suffix of the generic file name is. archiver.

This does not want to design cryptographic algorithms for those. The person who wants to encrypt the data is a good gospel.
A self-motivated management scheme that supports persistence, object graphs, and lifecycles.

Its data is also stored in the system database to apply the corresponding table, so it can be used to store confidential data (such as: username and password). Ability to store a variety of data. Data that is generally very large. such as: Picture. The trip record exists in the file sandbox. Not suitable for such object storage, unless your travel data is very confidential. And the data cannot be too large to consider object storage.

In strict sense, CoreData is a management scheme. His persistence can be stored in SQLite, XML, or binary files. As the official definition says, the role of CoreData is much more than storing data so simple that it can model objects throughout the application and manage them proactively. He and Microsoft's Mfc::carchive implementation of object persistence and anti-persistence is just as supportive of supporting functions that have serialization, decomposing objects into types of basic data types, such as strings, shaping numbers, floating-point data, characters. Because persisted object data is in one object, he facilitates data management.

Therefore, using CoreData to store data does not require the use of NSUSERDEFAULTS data to store data.


-(ID) initwithdictionary: (nsdictionary*) dic
{
if (Self=[super init])
{
self.sex=[dic[@ "Sex"] intvalue];
self.driveryear=[dic[@ "Driveryear"] intvalue];
}

return self;

}

-(void) Encodewithcoder: (Nscoder *) Acoder
{
[Acoder encodeobject:[nsnumber numberWithInt:self.driverId] forkey:@ "id"];
[Acoder encodeobject:[nsnumber numberWithInt:self.sex] forkey:@ "sex"];

}
-(ID) Initwithcoder: (Nscoder *) Adecoder
{
if (Self=[super init])
{
Self.sex=[[adecoder decodeobjectforkey:@ "Sex"] intvalue];
Self.driveryear=[[adecoder decodeobjectforkey:@ "Driveryear"] intvalue];
}
return self;
}

//Clean up user information- (void) clearuserinfo{NSString*documents = [Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask,YES) Lastobject];NSString*path = [Documents stringbyappendingpathcomponent:@"User.archiver"];    User *user; [Nskeyedarchiver Archiverootobject:user Tofile:path];}//Save-(void) Saveinfo: (User *) user{if(Nil! = user) {NSString*documents = [Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask,YES) Lastobject];NSString*path = [Documents stringbyappendingpathcomponent:@"User.archiver"];    [Nskeyedarchiver Archiverootobject:user Tofile:path]; }}//Get user information-(User *) GetUserInfo; {NSString*documents = [Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask,YES) Lastobject];NSString*path = [Documents stringbyappendingpathcomponent:@"User.archiver"];//extension can take whatever you wantUser *user = [Nskeyedunarchiver Unarchiveobjectwithfile:path];returnUser;}//Read the file from the object sandboxUser*user=[[globalshare Getglobalshare] GetUserInfo]; [Globalshare Getglobalshare]. User= user; [Globalshare Getglobalshare]. User. Orderlastlatitude=0;//Save on local[[Globalshare Getglobalshare] saveinfo:user];

Third method: File sandbox storage
Store non-confidential data primarily. Large data.

such as: Download the picture, no key value of the branch record. Note that if the system is cracked, the files in your sandbox can be obtained by others.

This method is very easy to operate. I don't know why a lot of articles about data storage are ignoring the most common and straightforward way to do this.

File sandbox frequently used files are usually stored in the Document Files folder (nsdocumentdirectory non-cracked system, users can directly see) and cached Documents folder (nscachesdirectory non-cracked system, the user is not visible).

Looks like the world article a big copy Ah!


Write a file
+ (void) Writetodocumentwithimagedata: (nsdata ) data name: (NSString ) fileName
{
NSString *path = [self filepath:filename];

[data writeToFile:path atomically:YES];

}
Get file path
+ (nsstring*) FilePath: (nsstring*) FileName {
nsarray* mypaths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);
nsstring* Mydocpath = [Mypaths objectatindex:0];
nsstring* FilePath = [Mydocpath stringbyappendingpathcomponent:filename];
return filePath;
}
Fourth method: Database storage
The library for SQLite is preset in the iOS SDK. Developers can build their own SQLite database.

Each time SQLite writes data, it generates IO consumption and archives the data to the appropriate file.


SQLite's well-handled data types are virtually identical to nsuserdefaults, and are basic types of small data that are only different from organizational forms.

Developers can organize data in a relational database, using SQL DML to manage the data. In general, the formatted text class data in the application can be stored in the database, especially similar chat records, timeline and other data with conditional query and ordering requirements.


Whether you take the system or you use it. The data storage nature of the sqlight third-party library is stored in the database and is not required to be classified separately. Data storage is a bit cumbersome, and storage is slow, and only the places that are really needed are used in this way. such as: Chat history, map geographic information query.

iOS four ways to store data and pros and cons

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.