Plist file and NSUserDefault file storage class, json format parsing, nsuserdefajson json

Source: Internet
Author: User

Plist file and NSUserDefault file storage class, json format parsing, nsuserdefajson json

======================================

File Operations

======================================

△1. plist File

The. plist file is a property dictionary array file;

The. plist file can be used to store dictionary, array, string, and other object data.

 

[Note] in iOS development, plist files are generally used for app configuration information.

[Note] multiple plist files can coexist in ios development projects.

[Note] plist files are used to store small amounts of data.

Advantage: easy to visualize and edit

Operations on plist files

// Example

NSString * str = @ "I am \" American \ "\ n, I love \" America \"";

NSLog (@ "% @", str );

1. Create a plist File

NSMutableDictionary * dic = [[NSMutableDictionary alloc] init];

 

[Dic setObject: @ "Zhang San" forKey: @ "name"];

[Dic setObject: @ "" forKey: @ "name1"];

[Dic setObject: @ "" forKey: @ "name2"];

// [Note] If the key is the same, the data will be washed out.

[Dic setObject: @ "zhangsan" forKey: @ "name"];

// Write data to a file

// [Understanding] atomically

// Atomically: parameter meaning, atomic operation

// If the atomically parameter is yes, the program will back up the data and write all the data to the cache before writing the data to the file at one time.

// If the atomically parameter is no, the program will directly write the data to the cache.

[Dic writeToFile: Path atomically: YES];

2. Create a multi-key plist File

NSMutableDictionary * plugin1 = [[NSMutableDictionary alloc] init];

[Plugin1 setObject: @ "Zhang San 1" forKey: @ "name1"];

[Plugin1 setObject: @ "" forKey: @ "name2"];

NSMutableDictionary * plugin2 = [[NSMutableDictionary alloc] init];

[Plugin2 setObject: @ "" forKey: @ "name1"];

[Plugin2 setObject: @ "Zhao Wu" forKey: @ "name2"];

NSMutableDictionary * listDic = [[NSMutableDictionary alloc] init];

[ListDic setObject: plugin1 forKey: @ "First Class"];

[ListDic setObject: plugin2 forKey: @ ""];

[ListDic setObject: @ "" forKey: @ "name"];

[ListDic writeToFile: Path atomically: YES];

3. Modify an attribute

// Read the current plist file and read all data first.

// Read the file content in the specified directory

NSMutableDictionary * appList = [[NSMutableDictionary alloc] initWithContentsOfFile: Path];

[AppList setObject: @ "" forKey: @ "name"];

NSMutableDictionary * chu1 = [appList objectForKey: @ "First Class 1"];

NSString * name1 = [chu1 objectForKey: @ "name1"];

[[AppList objectForKey: @ "First Class"] objectForKey: @ "name1"];

// Re-combine a new content by extracting the content, and re-store the new content data into plist.

[Chu1 setObject: @ "qianfeng" forKey: @ "name1"];

[AppList setObject: chu1 forKey: @ "First Class"];

[AppList writeToFile: Path atomically: YES];

 

[Summary]

1. plist file operations are actually a dictionary with various nested operations on internal data.

2. If you want to modify the content of a field in plist, locate it at one layer, encapsulate it at the other layer, and write the file again. (File Overwrite process)

3. duplicate key values are not allowed in plist. If duplicate names exist, the values under the previous names are washed out.

 

Ii. NSUserDefault class for file storage

1. NSUserDefault is a local data storage class that stores small data volumes.

2. NSUserDefault is often used in iOS to store users' personal information and login registration information.

 

[Note] the archive, file writing, and NSUserDefault files that you have learned so far are used to store small data volumes. They can store large data volumes but may cause performance problems. Database for storing large data volumes]

[Database]

1. For the underlying data of SQlite, you must manually create a database file (db) and manually write the sqlite statement;

2. [core data] is a database storage, query, modification, and deletion solution provided by Apple. The core data database is actually a class library encapsulated by sqlit3.

3. Third-party databases.

[Learn NSUserDefault]

// UserDefault Demo

// NSUserDefaults is a singleton class that calls the singleton method.

NSUserDefaults * defaul = [NSUserDefaults standardUserDefaults];

// Set the key and value

[Defaul setObject: @ "15588605664" forKey: @ "userName"];

[Defaul setObject: @" 123456 "forKey: @" password "];

 

NSArray * classInfo = @ [@ "First Class", @ "66 students", @ "average score 99.98", @ {@ "key ": @ "value"}];

[Defaul setObject: classInfo forKey: @ "clss_Info"];

 

[Defaul setObject: @ "1" forKey: @ "status"];

[Defaul setBool: YES forKey: @ "status"];

[Defaul setInteger: 1 forKey: @ "int"];

[Defaul setObject: [NSNumber numberWithBool: YES] forKey: @ "status1"];

[Defaul setFloat: 0.15 forKey: @ "float"];

// Store the content you just set to the space file allocated by NSUserDefaults.

// The system will put all the files stored in NSUserDefaults to a specified directory of the app. In fact, this directory is under a new directory under the library directory of the root directory.

// You must write this method to ensure that the data is safe. If you do not write this method, the data may not be saved successfully, for example, data is saved in multiple threads;

[Defaul synchronize];

// ========================================

// File Reading Method

NSString * userName = [defaul objectForKey: @ "userName"];

NSString * pwd = [defaul objectForKey: @ "password"];

// If key and value are involved, how to write the key during storage and how to write the key during retrieval

// If key and value are involved, if the stored key is the same, it will certainly Overwrite

NSArray * ClassAllInfo = [defaul objectForKey: @ "clss_Info"];

BOOL isok = [defaul objectForKey: @ "status"];

Float f1 = [defaul floatForKey: @ "float"];

NSInteger I = [defaul integerForKey: @ "int"];

BOOL B = [defaul boolForKey: @ "status"];

NSLog (@ "user login information: \ n % @", userName, pwd );

NSLog (@ "% @", ClassAllInfo );

[Note] NSUserDefault can store data types such as NSNumber (NSInterger, flost, and double), NSDictionary, NSArray, Bool, and NSString.

 

Delta. [extended knowledge-escape characters in C Language]

Escape characters are used to solve the Encoding Error Caused by some special characters in the program. For example:

[Note] the escape character must be written before each character \

1 .'

2."

3. Press ENTER

4. A lot more

 

[Expansion]

1. in programming, it is best not to name files with Chinese characters, spaces, or special symbols (because the computer will escape Chinese characters, spaces, or special symbols)

2. Conversion Relationship between file and memory data

 

Cpu (computer processing data brain) all data is scheduled and executed according to cpu instructions

 

Local file --> memory (read process)

Memory --> local file (write process)

[Note] the variables or object variables defined in the Code are stored in the memory. If you want to retain some useful information permanently, you need to save the information to the file.

 

(1). The data in the memory is temporary data. When a computer experiences an unexpected situation (power failure), the data in the memory disappears;

(2). Write the input in the memory to the file and save it permanently as long as the file is not deleted.

 

Iii. json Format Parsing

1. json

2. xml

[Comparison] xml format appears earlier than json format. xml is a form (table) (<body> name </body> ), the most critical disadvantage of xml is that it is not readable, which makes parsing difficult for programmers. Xml is applied to a large amount of data. However, with the rise of mobile terminals, json format has also become popular. Gradually become a format for obtaining data from ios and Android apps. Json format advantages: the format is clear and can be used to obtain small data volumes.

// Example

# Import <Foundation/Foundation. h>

# Import "MyModel. h"

# Import "UserModel. h"

 

# Define PATH @ "http://m2.qiushibaike.com/article/list/latest? Page = 1 & count = 30 & rqcnt = 21 & r = a1ef5f561429944164282"

 

Int main (int argc, const char * argv []) {

@ Autoreleasepool {

// There are many protocols: http ftp mail file socket xmpp

// Url format: Protocol: // domain name (IP address): Port/path? Parameter List (separated)

// Convert the string to the NSURL type

NSURL * url = [NSURL URLWithString: PATH];

// Obtain data through url

// NSData * data1 = [[NSData alloc] initWithContentsOfFile: @ ""];

NSData * data = [[NSData alloc] initWithContentsOfURL: url];

// NSLog (@ "% @", data );

NSError * error = nil;

// NSJSONSerialization the Apple system provides resolution. This method parses data into NSDictionary to read variable content.

NSDictionary * dic = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: & error];

If (error ){

NSLog (@ "resolution failed ");

Exit (-1 );

}

NSLog (@ "% @", dic );

NSArray * array = [dic objectForKey: @ "items"];

// NSLog (@ "% @", array );

// Create a variable array to store the myModel model.

NSMutableArray * dataArray = [[NSMutableArray alloc] init];

For (int I = 0; I <array. count; I ++ ){

MyModel * myModel = [[MyModel alloc] init];

NSDictionary * dicItem = array [I];

// The key here must correspond to the field value returned by the url

MyModel. content = [dicItem objectForKey: @ "content"];

MyModel. modelId = [dicItem objectForKey: @ "id"];

If (! [[DicItem objectForKey: @ "user"] isMemberOfClass: [NSNull class]) {

NSDictionary * userDic = [dicItem objectForKey: @ "user"];

UserModel * userModel = [[UserModel alloc] init];

// NSLog (@ "% @", [userDic objectForKey: @ "avatar_updated_at"]);

UserModel. avatar_updated_at = [userDic objectForKey: @ "avatar_updated_at"];

UserModel. created_at = [userDic objectForKey: @ "created_at"];

UserModel. last_device = [userDic objectForKey: @ "last_device"];

MyModel. user = userModel;

 

}

[DataArray addObject: myModel];

}

// NSLog (@ "variable array count: % lu", dataArray. count );

 

For (MyModel * myModel in dataArray ){

NSLog (@ "content: % @, modelId: % @", myModel. content, myModel. modelId );

UserModel * userModel = myModel. user;

NSLog (@ "Update Time: % @, Creation Time: % @, final device: % @", userModel. avatar_updated_at, userModel. created_at, userModel. last_device );

}

}

Return 0;

}

 

# Import <Foundation/Foundation. h>

# Import "UserModel. h"

 

@ Interface MyModel: NSObject

@ Property (nonatomic, copy) NSString * content;

@ Property (nonatomic, copy) NSString * modelId;

@ Property (nonatomic, strong) UserModel * user;

@ End

 

# Import <Foundation/Foundation. h>

 

@ Interface UserModel: NSObject

@ Property (nonatomic, copy) NSString * avatar_updated_at;

@ Property (nonatomic, copy) NSString * created_at;

@ Property (nonatomic, copy) NSString * last_device;

@ End

[Note] can use http://www.bejson.com/json format validation and regular.

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.