IOS Data Access and Object serialization

Source: Internet
Author: User

I. Use the NSKeyedArchiver class to operate on Object Access

Features: This class can store objects in the form of key-value pairs and extract them from the file using keys. It is similar to SharedPreference in android and Its serialized data is encrypted.

1. Save data to a file:

NSString * rootDir = NSHomeDirectory (); NSString * path = [rootDir stringByAppendingPathComponent: @ "test.txt"]; NSMutableData * data = [NSMutable data]; NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc] initForWritingMutableData: data]; NSArray * array = @ [@ "one", @ "two"]; [archiver encodeInt: 100 forKey: @ "age"]; // equivalent to putInteger (key, value) of SharedPreference; [archiver encodeObject: array forKey: @ "names"]; // [archiver finishEncoding]; // if this method is called, data is stored in data [archiver release]; if ([data writeToFile: path atomically: YES]) {NSLog (@ "Object saved to file succeeded ");}

2. extract data from the file

NSData * data = [NSData failed: path]; NSKeyedArchiver * unarchiver = [[NSKeyedArchiver alloc] initForReadingWithData: data]; int age = [unarchiver decodeIntForKey: @ "age"] // obtain the value NSArray * array = [unarchiver decodeObjectForKey: @ "names"]; [archiver release];

Ii. Use the NSUserDefaults class to access objects

Features: This class stores objects in the system's fixed plist cache file in the form of key-value pairs, and extracts the objects from the file using the key, which is the same as SharedPreference in android Application scenarios, used to cache small and simple cache data

// 1. store Data NSArray * array = @ [@ "abc", @ "d"]; NSUserDefaults * userDefault = [NSUserDefaults standardUserDefaults]; [userDefault setInteger: 123 forKey: @ "number"]; [userDefault setObject: array forKey: @ "array"]; [userDefault synchronize]; // save to file // 2. NSInteger number = [userDefault integerForKey: @ "number"]; NSArray * array = [userDefault objectForKey: @ "array"];











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.