IOS app development video tutorial note (12) Persistence

Source: Internet
Author: User

This lesson focuses on the principles of final projects and persistence.

Persistence

Persistence means that it still exists when you exit the app. Nsuserdefaults is a very simple persistence solution, but there are restrictions, it can only be small things, usually some user options.

How can we make things of big data persistent?

The first method is to make things persistent. The first simple method is a bit like the evolutionary version implemented by using the property list in nsuserdefaults. property list is a custom concept, is a combination of nsarray, nsdictionary, nsnumber, nsstring, nsdate, and nsdata. All of the above APIs can be used for saving, and nsuserdefaults also has some APIs.

There is also an important method writetourl: atomically: In nsdata, nsarray, and nsdictionary. This method is to write an array to the URL indicated by a file system. atomically, if the file already exists, it moves the file aside, writes it to a new file, and closes the new file. In fact, it is written to a temporary named file, and then switched it off and removed the other one. It is a bit Atomic. If it cannot be written in half, it will stop. After writetourl, you can use initwithcontentsofurl or datawithcontentsofurl to retrieve things. These read/write methods, whether sent to nsdata, nsarray, or nsdictionary, are intended to allow an object of the same type to be read back, which can be internal properties
List.

Another class is called nspropertylistserialization. What it does is to convert the property list to nsdata, and vice versa. In this way, the property list can be converted into a heap of binary numbers and then written to the disk or stored in the network. You can also read a bunch of binary data through the network and then convert them back to the property list through nspropertylistserialization.

Another method of storage is to save archiving objects through the arbitrary graphs of objects.

Store things in the file system.

Then SQLite

The header of persistent storage is core data, which is an object-oriented database mechanism on the top of SQL.

Archiving

There are many traps in object graph archiving, and archive is suitable for circular graphs. Archiving can find that the object or pointer actually points to each other, and then restore the pointer when unarchives. However, you need to think clearly to make the object graph you build meaningful. The best example may be the view level created in xcode.

When you drag something from the object library to the screen, you are instantiating uiview and instantiating uiviewcontroller. They are all generic, so you need to change their classes on the inspector panel.

Basically, all objects in this topology must implement the nscoding protocol. There are two important methods in this Protocol:

- (void)encodeWithCoder:(NSCoder *)coder; - initWithCoder:(NSCoder *)coder;

The first is to put yourself into archive, and the second is to extract you from archive for use. This is why viewcontroller does not need to call their specified initialization when it appears on the storyboard, because they use this initialization set. The archive system implements alloc initwithcoder for them because they used encodewithcoder to save themselves. Initwithframe is not called in uiview, but is replaced by encodewithcoder and initwithcoder corresponding to frame.

- (void)encodeWithCoder:(NSCoder *)coder {      [super encodeWithCoder:coder];      [coder encodeFloat:scale forKey:@“scale”];      [coder encodeCGPoint:origin forKey:@“origin”];      [coder encodeObject:expression forKey:@“expression”];}

Make sure that initwithcoder and encodewithcoder correspond to each other.

- initWithCoder:(NSCoder *)coder {      self = [super initWithCoder:coder];      scale = [coder decodeFloatForKey:@“scale”];      expression = [coder decodeObjectForKey:@“expression”];      origin=[coderdecodeCGPointForKey:@“origin”]; //notethatorderdoesnotmatter}

How can we achieve this? Class methods in nskeyedarchiver:

+ (NSData *)archivedDataWithRootObject:(id <NSCoder>)rootObject;

You can pass a root object. For example, the root object in the storyboard may be the top-level view controller. All you need to do is ensure that all the objects in it implement the nscoder protocol.

Class methods in nskeyedunarchiver:

+ (id <NSCoder>)unarchiveObjectWithData:(NSData *)data;

On the contrary, you provide an archived nsdata and then return the root object of the Code.

id <NSCoder> object = ...; NSData *data = [NSKeyedArchiver archivedDataWithRootObject:object]; id <NSCoder> dup = [NSKeyedArchiver unarchiveObjectWithData:data];

If an object exists, obtain the nsdata about the object through the second row.

If an encode view archives its super view, you will be denied unless it is at the correct level. If it is at the top, it will be denied, but if it is inside, it will be executed.

File System

IOS is UNIX-based, and the underlying is a UNIX file system. It is protected by a file system. It is impossible to see everything and cannot be written at will.

Only data can be written in sandbox. Why? For security. When an app is deleted from a device, all related data is also deleted. By performing write operations in the sandbox, all application items, whether created by the user or created by the application in the sandbox, will be removed.

What is sandbox? There is a bundle directory for the application. The application is not a large binary file, but actually a directory, it contains executable programs, binary files, storyboard, and dragged images. Everything is in it. This is the bundle of the application. The directory in the sandbox itself is not writable and cannot be written into the directory. This is basically a read-only copy of the app created with xcode. The documents directory is an important directory in sandbox, which is used to store documents that are considered as their own by users. There is also a cache directory, which is something we have written here. Users generally do not think this is a document, and the existence of these documents is too short to affect users. The key in documentation is nssearchpathdirectory.

How can we get these directories and the URLs of these directories? If you want to write data in the application directory but cannot write data, you must copy the content in the application package to any writable place in the sandbox and then write data in it. If you want to connect a database to your app or write it to those databases, You have to copy them, whether copying them to the document directory or cache directory, you can write them.

How can we get the paths of these directories? Use this method:

- (NSArray *)URLsForDirectory:(NSSearchPathDirectory)directory                        inDomains:(NSSearchPathDomainMask)domainMask; //NSUserDomainMask

There is an API in nsurl to get a list of URLs, but you have to pass in the desired directory type, such as the document directory and cache directory. The above methods and nsurl Methods return an array of the path, so when I request the cache directory, I will get a URL array or an array of path strings.

Nsfilemanager provides practical operations for the file system, which is not a class used to read and write their own files. You can use it to find out the size of the file, delete the old cache files to be kicked out, or use it to find out, for example, when the application starts, what files are included in the cache. It is thread-safe, as long as the same instance is not used in two different threads.

Nsstring also has some file system related things, especially the Creation Path. Generally, nsurl is used to specify a link, and sometimes a string is used to construct a URL.

- (NSString *)stringByAppendingPathComponent:(NSString *)component;

This allows you to add content in a path. You can also write the string content to a file. You must specify the encoding type, such as ASCII, isolatin1,

- (BOOL)writeToFile:(NSString *)path         atomically:(BOOL)flag            encoding:(NSStringEncoding)encoding //e.g.ASCII,ISOLatin1,etc.              error:(NSError **)error;

You can also read the string from the file:

- (NSString *)stringWithContentsOfFile:(NSString *)path                          usedEncoding:(NSStringEncoding *)encoding                                  error:(NSError **)error;
SQLite

SQLite refers to the SQL file stored in a single file and stored in a single file. It is fast and only occupies a small amount of memory. It is a real SQL statement based on transaction processing. This is not a server-based SQL, but a file-based SQL, so it is concurrent. If there are two threads in the app, they must be written to the SQL database, which can run normally. However, it only performs simple thread locking and concurrency.

The following is its API:

intsqlite3_open(constchar*filename,sqlite3**db); //get a database into db int sqlite3_exec(sqlite3 *db,    // execute SQL statements                 const char *sql,                  int (*callback)(void *, int, char **, char **),                  void *context,                  char **error);int mycallback(void *context,int count,char **values,char **cols); //data returned int sqlite3_close(sqlite3 *db);    // close the database

When you open the SQL file, you will get a SQL database pointer and then execute the SQL statement. Submit your SQL statement to the database. Some SQL statements will call back and return the data you requested to you in a table. The returned data may also be an error. The callback function is usually in the following format:

int mycallback(void *context,int count,char **values,char **cols);

Then you can close it. The third line is const char * SQL, where the SQL statement is executed.

Original article: Click to open the link

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.